kun said:
Hi, Can you guys help me figure out the performance of each of these
statements.
First of all: Performance should only be a deciding factor if it is
a problem. I.e., make some performance measurements before changing
anything.
Second: You ask about the performance of a language construction in
a language with no guaranteed performance requirements. I.e., it's
entirely up to the implementation.
That said, there are some general characteristics of Javascript that
suggests which is likely to be faster, if any.
Which is faster?
1. Making a new Array using
- var new_list = new Array(); or
- var new_list = []
The latter is likely to be slightly faster. The former must do a
variable lookup on the global object to find the Array constructor,
which is likely to give it a slight overhead.
The way I would test it is to run a simple test like:
var x,i;
var t0 = new Date();
for(i = 0; i < 1000000; i++) {
x = new Array();
}
var t1 = new Date();
for(i = 0; i < 1000000; i++) {
x = [];
}
var t2 = new Date();
alert([t1-t0,t2-t1]);
In my Firefox, the results are approx. 877,570.
2. Appending element using
- push('a')
or if i know the index, new_list;
The push function must be looked up as a property of the object (it
might not be the build-in version) and it is variadic (can take an
arbitrary number of arguments), which means that the method call
must pass not only the single argument, but also the number of
arguments. Again, this suggests a slight overhead over the direct
property access, which is detectable as such at parse time.
I change the bodies of the loops in the test above to:
x.push(42);
and
y = 42;
(where x and y are initialized as empty arrays).
Firefox actually shows no discernible difference.
Safari 4 is actually a little faster doing push than assigning
to a numbered property, so is Chrome.
So much for my intuition.
3. ternary operator or
if() else ()
These are actually different in behavior.
If the branches contain a simple expression where the result can
be ignored, I expect them to behave identically.
And they do in Firefox.
4. Trying to make isodd function
which is faster (! (is_even)) or (x%2!=0)
Likely the latter, as the former performs a function call to
is_even (if I understand the question correctly) which does
the same computation as the latter does directly.
5. foreach or normal iteration
What is foreach?
/L