On May 25, 11:21 pm, Oliver Leics <
oliver.le...@gmail.com> wrote:
> On Fri, May 25, 2012 at 9:50 PM, Jorge <
jo...@jorgechamorro.com> wrote:
> > It does not take 3 seconds to start it up.
>
> then i don't understand the numbers and teh method.
>
> Please explain:
>
> $ time node -e 'i=1e7; while(i--);'
>
> real 0m2.029s
> user 0m2.008s
> sys 0m0.016s
>
> Those 2.029s really exclude startup time?
>
> The 'time' command itself excludes them?
Startup time should be in the order of 10s of milliseconds, so that's
not it. However, there's a simple explanation for it.
First of all, notice that `node -e` uses `eval()` (see
https://github.com/joyent/node/blob/82bcdbb8aaa4cf58917dc8d3fd4fcfc272512a2c/src/node.js#L264).
* node -e "var i=1e7;while(i--);"
This defines a new local variable in the context of the function that
called eval, unless there already was one there. v8 cannot optimize
functions where the scope of variables can be changed dynamically; it
can only optimize when it can statically determine whether a variable
is a local, or closure scoped, or a global object property.
* node -e "(function test() { var i=1e7;while(i--); })()"
This doesn't get optimized, but since v8 is certain that `var i` is a
local here, the generated code is reasonably efficient anyway.
* echo "i=1e7;while(i--);" > test.js && node test.js
`i` is a global variable here. Global variables are slow in non-
optimized code, but since no weird scope resolution corner cases are
present, v8 is able to detect that this is a 'hot' function and
optimize it. Hence, it is also reasonably fast.
* echo "var i=1e7;while(i--);" > test.js && node test.js
This is probably as fast as it gets, since it is both optimizable and
`var i` is a local.
The fact that node uses eval() might be considered a bug. However it
is highly unlikely that it will make your programs slow, since you
won't be running it with `node -e`.
(And I am sort of disappointed that the thread starter didn't figure
it out himself - I mean, it's like 20 seconds work to put the
offending code in a .js file and figure out that it's not slow at all.
It looks a lot like "sensationalist benchmarking" to me.)
- Bert