Reputation: 458
At 5:40 in this video he says that the non-blocking version (using fs.readFile instead of fs.readFileSync) is reading the files in parallell, thus being faster. How can this be if Node.js is single-threaded?
Blocking:
var callback = function(err, contents) {
console.log(contents);
}
fs.readFile('/etc/hosts', callback);
fs.readFile('/etc/inetcfg', callback);
Non-blocking:
var callback = function(err, contents) {
console.log(contents);
}
fs.readFileSync('/etc/hosts', callback);
fs.readFileSync('/etc/inetcfg', callback);
Which one is fastest and is the video correct?
Upvotes: 0
Views: 3028
Reputation: 29983
It is questionable whether that simple example can gain any advantages in terms of performance by choosing one instead of another. The main differences are that fs.readFileSync
will immediately read the contents of the file, resuming to the next instruction only when it is done. On the other hand, the asynchronous fs.readFile
will issue the reading procedure to the system and listen to incoming data without blocking.
It is true that the asynchronous version may read both files in parallel, but in the background this always involves file I/O operations that often cannot be performed simultaneously. How fast it can get also depends on the file system implementation and the underlying hardware device. If the I/O device is fast and can perform concurrent file reads, then Node.js will definitely take advantage of that with its non-blocking approach. Using multiple threads, which is less common, would not help because the IO device is the bottleneck. If the files are very large, both non-blocking and blocking approaches may take a similar time to finish.
In practice however, it is preferable to use the non-blocking version, since it allows the application to use CPU time and attend to other devices without waiting for the files to be entirely read. This is often critical on server applications, which should accept client connections even when performing other I/O-intensive tasks. In fact, this question might also be of interest, which considers a case where readFileSync
appears to be faster, although still not recommended in the given context.
Upvotes: 2