Will use of the debugging feature console.log
reduce JavaScript execution performance? Will it affect the speed of script execution in production environments?
Will use of the debugging feature console.log reduce JavaScript execution performance? Will it affect the speed of script execution in production environments?
Of course, console.log()
will reduce your program's performance since it takes computational time.
Is there an approach to disable console logs in production environments from a single configuration location?
Put this code at the beginning of your script to override the standard console.log function to an empty function.
console.log = function () { };
The performance hit will be minimal, however in older browsers it will cause JavaScript errors if the users browsers console is not open log is not a function of undefined
. This means all JavaScript code after the console.log call will not execute.
You can create a wrapper to check if window.console
is a valid object, and then call console.log in the wrapper. Something simple like this would work:
window.log = (function(console) {
var canLog = !!console;
return function(txt) {
if(canLog) console.log('log: ' + txt);
};
})(window.console);
log('my message'); //log: my message
Here is a fiddle: http://jsfiddle.net/enDDV/
Actually, console.log
is a lot slower than an empty function. Running this jsPerf test on my Chrome 38 gives stunning results:
console.log
is about 10 000 times slower than calling an empty function,Not that you'll notice the performance lag if you have a reasonable number of console.…
calls firing once (a hundred will take 2 ms on my install of Chrome – or 20 ms when the console is open). But if you log stuff to the console repeatedly – for instance, hooking it up through requestAnimationFrame
– it can make things janky.
In this test I've also checked out the idea of a custom “hidden log” for production – having a variable which holds log messages, available on demand. It turns out to be
console.log
,