Will console.log reduce JavaScript execution performance?

前端 未结 9 1268
半阙折子戏
半阙折子戏 2020-12-24 00:03

Will use of the debugging feature console.log reduce JavaScript execution performance? Will it affect the speed of script execution in production environments?

9条回答
  •  清歌不尽
    2020-12-24 00:51

    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/

提交回复
热议问题