fs.readFileSync seems faster than fs.readFile - is it OK to use for a web app in production?

前端 未结 5 1049
难免孤独
难免孤独 2020-12-05 13:19

I know that when developing in node, you should always try to avoid blocking (sync) functions and go with async functions, however I a little test to see how they compare.

5条回答
  •  再見小時候
    2020-12-05 13:44

    I've tried to check the real, measurable difference in a speed between fs.readFileSync() and fs.readFile() for downloading 3 different files which are on SD card and I've added between this downloads some math calculation and I don't understand where is the difference in speed which is always showed on node pictures when node is faster also in simple operation like downloading 3 times the same file and the time for this operation is close to time which is needed for downloading 1 time this file.

    I understand that this is no doubtly useful that server during downloading some file is able to doing other job but a lot of time on youtube or in books there are some diagrams which are not precise because when you have a situation like below async node is slower then sync in reading small files(like below: 85kB, 170kB, 255kB).

    var fs = require('fs');
    
    var startMeasureTime = () => {
      var start = new Date().getTime();
      return start;
    };
    
    // synch version
    console.log('Start');
    var start = startMeasureTime();
    
    for (var i = 1; i<=3; i++) {
      var fileName = `Lorem-${i}.txt`;
      var fileContents = fs.readFileSync(fileName);
      console.log(`File ${1} was downloaded(${fileContents.length/1000}KB) after ${new Date().getTime() - start}ms from start.`);
    
      if (i === 1) {
        var hardMath = 3*54/25*35/46*255/34/9*54/25*35/46*255/34/9*54/25*35/46*255/34/9*54/25*35/46*255/34/9*54/25*35/46*255/34/9;  
      };
    };
    
    // asynch version
    setImmediate(() => {
      console.log('Start');
      var start = startMeasureTime();
    
      for (var i = 1; i<=3; i++) {
        var fileName = `Lorem-${i}.txt`;
        fs.readFile(fileName, {encoding: 'utf8'}, (err, fileContents) => {
          console.log(`File ${1} was downloaded(${fileContents.length/1000}KB) after ${new Date().getTime() - start}ms from start.`);
        });
    
        if (i === 1) {
          var hardMath = 3*54/25*35/46*255/34/9*54/25*35/46*255/34/9*54/25*35/46*255/34/9*54/25*35/46*255/34/9*54/25*35/46*255/34/9;  
        };
      };
    });
    
    This is from console:
    Start
    File 1 was downloaded(255.024KB) after 2ms from start.
    File 1 was downloaded(170.016KB) after 5ms from start.
    File 1 was downloaded(85.008KB) after 6ms from start.
    Start
    File 1 was downloaded(255.024KB) after 10ms from start.
    File 1 was downloaded(85.008KB) after 11ms from start.
    File 1 was downloaded(170.016KB) after 12ms from start.
    

提交回复
热议问题