Read json file content with require vs fs.readFile

前端 未结 7 2002
说谎
说谎 2020-11-30 03:46

Suppose that for every response from an API, i need to map the value from the response to an existing json file in my web application and display the value from the json. Wh

7条回答
  •  暖寄归人
    2020-11-30 04:19

    Since no one ever cared to write a benchmark, and I had a feeling that require works faster, I made one myself.

    I compared fs.readFile (promisified version) vs require (without cache) vs fs.readFileSync.

    You can see benchmark here and results here.

    For 1000 iterations, it looks like this:

    require: 835.308ms
    readFileSync: 666.151ms
    readFileAsync: 1178.361ms
    

    So what should you use? The answer is not so simple.

    1. Use require when you need to cache object forever. And better use Object.freeze to avoid mutating it in application.
    2. Use readFileSync in unit tests or on blocking application startup - it is fastest.
    3. Use readFile or promisified version when application is running and you don't wanna block event loop.

提交回复
热议问题