jsbench002

In this test we measure the speed of getElementById(). The first function simply run getElementById multiple times on the same object. The second function use a global var instead. Test 1
function init we simply create a div and set the a array function f1 document.getElementById is executer for every loop cycle function f2 we use a global var poiting to the div
As you can see, using a global object is far more faster.. f1 took:1329ms f2 took:4ms [FF 3.5.2] f1 took:1942ms f2 took:4ms [FF 3.5.2]
Conclusion: if possible, always cache getElementById.

Now, given that using global variables is always a bad thing ... Let's try it with a local var instead: Test2
Using a local variable is a good thing... f1 took:1255ms f2 took:3ms [FF 3.5.2] f1 took:1349ms f2 took:3ms [FF 3.5.2]
Conclusion: global vars are bad, messy and slow down your code.


Leave a Reply

 (required)

plain