Is reading a file on UNIX faster than writing a file

filesfilesystemshard-disk

A rather obtuse performance bottleneck has boiled down to this very small query. I have done some empirical analysis and I think I might be getting victimized by disk caching strategies. Fundamentally (if disk caching were disabled) would writing a file be as fast, slower, or faster than reading a file? I would assume that the answer would depend on the fragmentation (and file size) but the operation to write a file would have to do an additional look up of where the next free block is rather than just following the pointer to it.

Best Answer

It depends. There is no general answer to this question.

In the absence of caching, writing a disk file is usually measurably slower than reading. This has little to do with the operating system and everything to do with the hardware: both hard disks and solid state media read faster than they write. A secondary factor is related to filesystem structure: reading only needs to traverse the directory tree and block list down to the data, then read the data, whereas writing needs to perform the same traversal, then write the data, then update some metadata.

When caching comes into play, things change. Reading data that's in cache is very fast, but reading data that isn't in cache has to go and fetch it from the disk. Operating systems might try to anticipate reads, but that only works in very specific cases (mainly sequential reads from a file). Writing, on the other hand, can be near-instantaneous as long as the amount of data isn't too large, as the data is only written to a memory buffer. The buffer has to be written to disk eventually, but by that time your application has already moved on to do more stuff.