JavaScript:缓存嵌套变量的速度更快吗?

编程入门 行业动态 更新时间:2024-10-24 16:23:40
本文介绍了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这样的工具中测试你的具体情况,这样你就可以测量你关心的确切情况,你也应该在多个浏览器中运行测试,以确保你测量的是语言实现的一般特征,而不是只是一个浏览器的特性。

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

在具体示例中,我在此编码: jsperf / 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 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: jsperf/cache-deep-reference, the cached reference was more than 2x faster in chrome and more than 4x faster in IE10.

更多推荐

JavaScript:缓存嵌套变量的速度更快吗?

本文发布于:2023-06-01 10:27:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/412948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   更快   缓存   变量   速度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!