mirror of
https://github.com/github/codeql.git
synced 2025-12-24 20:56:33 +01:00
70 lines
2.1 KiB
XML
70 lines
2.1 KiB
XML
<!DOCTYPE qhelp PUBLIC
|
|
"-//Semmle//qhelp//EN"
|
|
"qhelp.dtd">
|
|
<qhelp>
|
|
|
|
<overview>
|
|
<p>
|
|
A for-in loop whose iteration variable is a property, a global variable, a local variable from
|
|
a surrounding scope, or a local variable that is captured in a closure may prevent optimization
|
|
of the function it appears in, which could make the program run slower. The same applies to
|
|
for-of loops.
|
|
</p>
|
|
|
|
<p>
|
|
In particular, the V8 engine (which is used by the Google Chrome browser and the Node.js platform)
|
|
does not currently optimize functions containing such loops.
|
|
</p>
|
|
|
|
</overview>
|
|
<recommendation>
|
|
|
|
<p>
|
|
Turn the iteration variable into a local variable if possible.
|
|
</p>
|
|
|
|
</recommendation>
|
|
<example>
|
|
|
|
<p>
|
|
In the following example, function <code>extend</code> copies all properties of its argument
|
|
<code>src</code> into object <code>dest</code> using a for-in loop. Note, however, that
|
|
the loop variable <code>p</code> is not declared in <code>extend</code>, and
|
|
thus is interpreted as a global variable.
|
|
</p>
|
|
|
|
<sample src="examples/NonLocalForIn.js" />
|
|
|
|
<p>
|
|
However, this is clearly just a typo, and the <code>p</code> should be declared as a local variable instead:
|
|
</p>
|
|
|
|
<sample src="examples/NonLocalForInGood.js" />
|
|
|
|
<p>
|
|
As another example, consider the following generalization of <code>extend</code> that accepts zero
|
|
or more <code>src</code> objects:
|
|
</p>
|
|
|
|
<sample src="examples/NonLocalForIn2.js" />
|
|
|
|
<p>
|
|
Note that <code>p</code> is now a local variable, but it is declared in the outer function <code>combine</code>,
|
|
not in the inner function <code>extend</code> where it is actually used. The declaration should be moved
|
|
into <code>extend</code> as follows:
|
|
</p>
|
|
|
|
<sample src="examples/NonLocalForIn2Good.js" />
|
|
|
|
<p>
|
|
In those (rare) cases where the iteration variable really has to be a global variable or a property, you can
|
|
introduce a new, local iteration variable and copy its value into the desired global variable or property inside
|
|
the loop.
|
|
</p>
|
|
|
|
</example>
|
|
<references>
|
|
<li>Petka Antonov: <a href="https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#5-for-in">Optimization killers</a>.</li>
|
|
</references>
|
|
</qhelp>
|