Node.js console.log performance
If your Node.js code is littered with console.log statements are you inviting performance issue开发者_C百科s? Is it worth debug/production toggling this on/off? I realized logging is important to prod in general - but I'm generally curious if the console output has a performance hit?
In Chrome it definitely seems to degrade performance if the console is open.
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
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.
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(){};
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.
精彩评论