Do comments affect performance?

后端 未结 5 605
囚心锁ツ
囚心锁ツ 2021-02-05 11:05

Am I correct to say that JavaScript code isn\'t compiled, not even JIT? If so, does that mean that comments have an affect on performance, and I should be very careful where I p

5条回答
  •  有刺的猬
    2021-02-05 11:47

    Am I correct to say that JavaScript code isn't compiled, not even JIT?

    No. Although JavaScript is traditionally an "interpreted" language (although it needn't necessarily be), most JavaScript engines compile it on-the-fly whenever necessary. V8 (the engine in Chrome and NodeJS) used to compile immediately and quickly, then go back and aggressively optimize any code that was used a lot (the old FullCodegen+TurboFan stack); a while back having done lots of real-world measurement, they switched to initially parsing to byteocde and interpreting, and then compiling if code is reused much at all (the new Ignition+TurboFan stack), gaining a significant memory savings by not compiling run-once setup code. Even engines that are less aggressive almost certainly at least parse the text into some form of bytecode, discarding comments early.

    Remember that "interpreted" vs. "compiled" is usually more of an environmental thing than a language thing; there are C interpreters, and there are JavaScript compilers. Languages tend to be closely associated with environments (like how JavaScript tends to be associated with the web browser environment, even though it's always been used more widely than that, even back in 1995), but even then (as we've seen), there can be variation.

    If so, does that mean that comments have an affect on performance...

    A very, very, very minimal one, on the initial parsing stage. But comments are very easy to scan past, nothing to worry about.

    If you're really worried about it, though, you can minify your script with tools like jsmin or the Closure Compiler (even with just simple optimizations). The former will just strip comments and unnecessary whitespace, stuff like that (still pretty effective); the latter does that and actually understands the code and does some inlining and such. So you can comment freely, and then use those tools to ensure that whatever minuscule impact those comments may have when the script is first loaded is bypassed by using minifying tools.

    Of course, the thing about JavaScript performance is that it's hard to predict reliably cross-engine, because the engines vary so much. So experiments can be fun:

    • Here's an experiment which (in theory) reparses/recreates the function every time
    • Here's one that just parses/creates the function once and reuses it

    Result? My take is that there's no discernable difference within the measurement error of the test.

提交回复
热议问题