Difference between writing to file atomically and not

后端 未结 3 1379
孤城傲影
孤城傲影 2020-12-25 10:40

What is the difference in writing to files atomically on the iPhone in objective-c and not, is there any performance difference between the two?

相关标签:
3条回答
  • 2020-12-25 11:00

    Filesystems don't have to resort to write/rename cycles for atomic writes. Filesystems that have locking semantics allow you to 'lock' portions or all of a file, or in some cases even do things like appends to a file, to help with atomicity.

    @Randy, both your assumptions about fragmentation are likely to be wrong. On most filesystems, writing an entire file and closing it will result in a less fragmented file, and writing a large file in a single write will definitely result in better usage of large blocks. If you meant the file blocks were more likely to 'creep' across the disk, that depends on the layout preferences in your filesystem. If you're writing to flash, you probably want the filesystem to creep across the available storage as a sort of self-levelling of the writes.

    0 讨论(0)
  • 2020-12-25 11:08

    Atomic in general means the operation cannot be interrupted will complete or have no effect. When writing files, that is accomplished by writing to a temporary file then replacing the original with the temporary when the write completes.

    A crash while writing an atomic file means the original is not modified and there is a garbage file that can be deleted. A crash while writing normally would mean an expected good file is corrupt.

    Performance wise the cost is minimal. During the write you will have two copies of a file. The file replace is a very simple operation at the file system level.

    Edit: thanks zneak

    0 讨论(0)
  • 2020-12-25 11:14

    Writing atomically takes more steps - additionally auxiliary file is created. NSString Class Reference explains:

    If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

    Here is the example in the case of pLists:

    [array writeToFile:path atomically:YES];
    

    when "YES", then pList is updated just once even if you run the code several times in XCode,

    [array writeToFile:path atomically:NO];
    

    when "NO" it is updated as many as you run the same code (repeated update).

    0 讨论(0)
提交回复
热议问题