Node.js console.log performance

前端 未结 4 524
无人及你
无人及你 2021-02-01 04:15

If your Node.js code is littered with console.log statements are you inviting performance issues? Is it worth debug/production toggling this on/off? I realized logging is import

相关标签:
4条回答
  • 2021-02-01 04:48

    Edit:

    console.log is synchronous and it is blocking the event loop


    I think this is low hanging fruit, and will almost not give you any speed bump at all when you disable logging(if not used rigorously in critical parts). Probably the console.log is implemented in pure C. Also there are some modules available which can turn off logging in production, just as you can do with socket.io:

    • https://github.com/nomiddlename/log4js-node
    • https://github.com/visionmedia/log.js
    0 讨论(0)
  • 2021-02-01 04:53

    console.log calls in nodejs are synchronous(!) and block the event loop. I just experienced that when I logged the results from executing (asynchronous) sql queries with pg. Logging only 20 items and their (few) properties decreased the performance from 3ms to 300ms on my local machine.

    0 讨论(0)
  • 2021-02-01 04:54

    As said above, the console.log is asynchronous and non-blocking, so it would not slow your application too much except one tick for the function invocation.

    But it is a good habit to use some module to turn some logs of certain level off when deploy it in production instead of using console.log directly. There have been several good ones as @Alfred listed.

    The Nodejs official blog posted an article suggesting use JSON format for logging, check it out at Service logging in JSON with Bunyan, and Bunyan for nodejs is really worth trying.

    0 讨论(0)
  • 2021-02-01 05:00

    console.log slows down chrome because it is actually interfacing with the DOM on every call. The entire inspect element system is actually just tons of DOM elements. When you call console.log in the browser it it having to append a new element to the console on every call.

    You can see how console.log is really just HTML by right clicking on an element in console and clicking inspect element. This will in fact open a new console inspecting an already existing console. :D

    If you are really that worried about performance you could always remove the console.log feature completely(not really advised because it could get confusing). You basically can noop the function in the browser or server side. No more console.log no more speed impact :D

    console.log=function(){};
    
    0 讨论(0)
提交回复
热议问题