вторник, 11 сентября 2007 г.

Javascript performance nuances

We usually have some vague understanding of performance costs of this and that but just no time to measure them. Here are results of some javascript tests concerning performance. Test were performed on firefox 2.0.6.



Post-increment vs. pre-increment



I was taught on books that payed much (to much as for today's reality) attention to performance. One of the tricks to boost performance was using pre increment instead post increment wherever possible. The reason for this is that post version not only increments but also yields a temporary object, so the rule is the heavier the type you are working with the bigger is penalty of i++ vs. ++i.



In javascript the difference between pre and post versions of int are negligeable. I run a 10 million iterations loop
for(var i=0; i<10000000; ++i);
and
for(var i=0; i<10000000; i++);
Something interesting for me was that the former outperformed the later by only 300 milliseconds while the execution lasted about 2 seconds.



Javascript function call



Another test was the cost of function call. I've compared a time it takes to make a million of and of x = i and x = assign(i) where assign = function(i) {return i}. The result was the function version was five times slower! So you have to have a cause for using a function



Dot and braces accessors



What is a cost of using classes and arrays? Is there any? Whell there is no difference between a['x'] and a.x in terms of performance. But these are 20% slower then using a variable directly.



Regards,
Andrew

Комментариев нет: