简体   繁体   中英

Difference between writing to file atomically and not

在objective-c中在iPhone上原子地写入文件有什么区别,两者之间有什么性能差异?

Atomic in general means the operationcannot be interruptedwill 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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM