Testing Javascript loop performance
After a little discussion with Yoan I have had the desire to test different Javascript loop syntaxes. I have made a test Javascript page that use 5 different loops and mesure the time needed to run it.
Here is the result of my tests :
- Dumb standard loop
- Prefixed incrementation
- Prefixed incrementation with buffered test variable
- Prefixed decrementation with buffered test variable
- "For in" syntax
| Opera 9.10 |
1 : 37ms
2 : 37ms
3 : 33ms
4 : 28ms
5 : 74ms
|
| Konqueror 3.5.6 |
1 : 155ms
2 : 154ms
3 :145ms
4 : 134ms
5 : 3310ms a lot larger
|
| Firefox 2.0.0.2 |
1 : 220ms
2 : 220ms
3 : 221ms
4 : 154ms
5 : 348ms
|
These tests show interresting things :
- Opera 9 rule completly others browsers on these tests
- The prefixed decrementation loop with buffered test variable is the quicker in all browser
- Access the length attribute of an array costs almost nothing
- Prefixed incrementation is not better than postfixed
- "For in" syntax is the slower on all browser and painfully slow on Konqueror
So, for redeability, use 1 : the dumb way, for performance use 4. "For in" syntax is elegant but inneficient. Don't use 5 or only on a small amount of data.