Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - Creating local variable counterparts of global objects if used multiple times?

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

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

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...