Delen via


A tip for improving perf with JScript...

Most of you must be knowing this but still i find it useful to share...

"If you are calling a dom method again and again in your website then it is a good idea to cache it to improve performance."

For example, let's say you are calling a method window.X1.X2.CallFoo() in a loop...

for (i = 0; I < 10; I ++)
{
window.X1.X2.CallFoo()
}

If you change above your code to following then you will certainly gain some performance…

 

cacheFoo = window.X1.X2.CallFoo;

for (i = 0; I < 10; I ++)
{
cacheFoo();
}

 

Well, so far so good. But how come caching improves the perf/execution time while the same method in IE DOM is being called in both cases.

 

The answer lies in the binding logic JScript uses. In first case, in each iteration of the loop, JS first binds to window.X1 then X1.X2 and then calls the method in IE DOM. This binding to IE Dom elements/methods/properties has its own cost.

 

In the second case, binding happens only once, in the very first line where I am caching the method in a local variable. In this case IE creates a new dispatch object for Window.X1.X2.CallFoowhich is assigned to cacheFoo . Next time onwards JS can just call the method, it need not bind again.