Will console.log reduce JavaScript execution performance?

前端 未结 9 1210
半阙折子戏
半阙折子戏 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:28

    I do it this way to maintain original signature of console methods. In a common location, loaded before any other JS:

    var DEBUG = false; // or true 
    

    Then throughout code

    if (DEBUG) console.log("message", obj, "etc");
    if (DEBUG) console.warn("something is not right", obj, "etc");
    
    0 讨论(0)
  • 2020-12-24 00:37

    If you create a shortcut to the console in a common core script, eg:

    var con = console;
    

    and then use con.log("message") or con.error("error message") throughout your code, on production you can simply rewire con in the core location to:

    var con = {
        log: function() {},
        error: function() {},
        debug: function() {}
    }
    
    0 讨论(0)
  • 2020-12-24 00:38

    If you are going to have this on a public site or something, anyone with little knowledge on using the developer tools can read your debug messages. Depending on what you are logging, this may not be a desirable behavior.

    One of the best approaches is to wrap the console.log in one of your methods, and where you can check for conditions and execute it. In a production build, you can avoid having these functions. This Stack Overflow question talks in details about how to do the same using the Closure compiler.

    So, to answer your questions:

    1. Yes, it will reduce the speed, though only negligibly.
    2. But, don't use it as it's too easy for a person to read your logs.
    3. The answers to this question may give you hints on how to remove them from production.
    0 讨论(0)
  • 2020-12-24 00:45
    const DEBUG = true / false
    DEBUG && console.log('string')
    
    0 讨论(0)
  • 2020-12-24 00:45

    Any function call will slightly reduce performance. But a few console.log's should not have any noticeable effect.

    However it will throw undefined errors in older browsers that don't support console

    0 讨论(0)
  • 2020-12-24 00:47

    I made this jsPerf test: http://jsperf.com/console-log1337

    It doesn't seem to take any longer than other function calls.

    What about browsers that doesn't have a console API? If you need to use console.log for debugging, you might include a script in your production deployment to override the console API, like Paul suggests in his answer.

    0 讨论(0)
提交回复
热议问题