Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I recently read, that if a global object (i.e. document) is being called multiple times then it would increase performance of the JavaScript by encapsulating this object into a local variable.

For Example, this should technically run faster..

var doc = document;
var a = doc.getElementById("id1");
var b = doc.getElementById("id2");
var c = doc.getElementById("id3");

than this..

var a = document.getElementById("id1");
var b = document.getElementById("id2");
var c = document.getElementById("id3");

Does this performance increase remain true, even in high availability/offline capable web applications and single page applications? Will memory usage grow substantially by creating local variable counterparts of highly used global objects? Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
261 views
Welcome To Ask or Share your Answers For Others

1 Answer

Even though the statement is technically correct (the name resolution would be faster if a variable is declared in a current scope so that the interpreter doesn't traverse up checking every parent scope) - it's not what you generally need to do.

That's it - the given "optimization" will not give and measurable difference but will make the code more tricky.

Also don't forget the 1st optimization rule: measure first - then optimize what is slow. Is it slow what you're trying to optimize? Nope. Then leave it as-is.

Does this performance increase remain true, even in high availability/offline capable web applications and single page applications?

It remains "true" for every piece of code written in JS.

Will memory usage grow substantially by creating local variable counterparts of highly used global objects?

Nope, it should be pretty close (you're only assigning references, the actual objects are not being copied).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...