JavaScript:缓存嵌套变量的速度更快吗? [英] JavaScript: is it faster to cache deeply nested variables?

查看:65
本文介绍了JavaScript:缓存嵌套变量的速度更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个变量嵌套在一个巨大的对象中,我经常重复使用它:

  i = 10000000 ; 
而(i){
i--;
document.write(bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p);
}

将它缓存在循环外的新变量中会更快吗?

  v = bigobject.abcdefghijklmnop 

并在我的循环中使用该缓存变量?

  document.write(v); 

对于不那么视觉化的方式: JavaScript变量是自动缓存还是浏览器必须搜索每次请求时通过更大的变量?

解决方案

与所有重要性能问题一样,它总是最好的在jsperf.com这样的工具中测试你的具体情况,这样你就可以测量你关心的确切情况,你也应该在多个浏览器中运行测试,以确保你测量的是语言实现的一般特征,而不是只是一个浏览器的特性。



在回答你的问题时,如果要多次访问它,通常会更快地缓存深层对象引用。 / p>

在具体示例中,我在此编码: http://jsperf.com / cache-deep-reference ,缓存的引用在chrome中快了2倍多IE10中的速度提高了4倍以上。


Let's say I have a variable nested deeply within a massive object which I re-use quite often:

i = 10000000;
while (i) {
    i--;
    document.write( bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p );
}

Would it be faster to cache it in a new variable outside of the loop?

v = bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p

and use that cached variable in my loop?

document.write ( v );

For the less visually oriented: Are JavaScript variables cached automatically or does the browser have to search through the larger variable each time it's requested?

解决方案

As with all performance questions of importance, it is always best to test your specific situation in a tool like jsperf.com so you can measure the exact situation you care about and you should also run the test in multiple browsers to make sure what you're measuring is a general characteristic of the language implementation, not just a peculiarity to one browser.

In answer to your question, it is generally faster to cache a deep object reference if you are going to be accessing it multiple times.

In the specific example, I coded here: http://jsperf.com/cache-deep-reference, the cached reference was more than 2x faster in chrome and more than 4x faster in IE10.

这篇关于JavaScript:缓存嵌套变量的速度更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆