缓存 Array.length 是老生常谈的小优化
问题
缓存 Array.length 是老生常谈的小优化。
// 不缓存
for (var i = 0; i < arr.length; i++) {
...
}
// 缓存
var len = arr.length;
for (var i = 0; i < len; i++) {
...
}
// 或者
for (var i = 0, len = arr.length; i < len; i++) {
...
}
但以前写过 Java 的笔者一直对这种破碎的写法感到不适,也对这种写法的实际优化效果产生疑问。
且推崇这种写法的朋友似乎很多也是“前辈这么说+自己想了一下觉得有道理”。
由于 for 循环搭配 Array.length 是极度常用的 JavasScript 代码,所以还是有必要搞清楚的。
结论
经过一番摸索后笔者得到的结论是:缓存 Array.lengh 对优化的影响没有想象中的大,甚至可能会有所减慢。
理由
从测试结果上看
stackoverflow 上也有这个讨论,For-loop performance: storing array length in a variable 。
accepted 的答案是说缓存会起到加速的结果,给出了 jsPerf 测试。
但是有答案反对,也给出了 jsPerf 测试。
两个答案的区别在于“循环不变量代码移动(Loop-invariant code motion)”,accepted 答案的测试循环里没有访问到数组,是不实际的,后面会讲到。
从另一篇文章 Shoud I have to cache my array’s length? 的测试结果也可以看出缓存差别不大。
还有这篇 JavaScript's .length Property is a Stored Value
从 V8 的中间代码分析
这篇文章 How the Grinch stole array.length access 从 V8 的 hydrogen 探讨 Array.length 在 for 循环中的处理。
正如上面提到的“循环不变量代码移动”,V8 引擎会聪明的把能确定不变的代码移到循环外。
所以像下面这种代码也不会影响引擎对 Array.length 的优化:
function uncached(arr) {
for (var i = 0; i < arr.length; i++) {
arr[i]
}
}
而当在循环中调用函数时,V8 会尝试将函数进行内联,从而继续进行“循环不变量代码移动”优化。
但当函数不可内联时,V8 就没辙了,每次循环都要重新计算一遍 length
function BLACKHOLE(sum, arr) {
try { } catch (e) { }
}
function uncached(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
if (sum < 0) BLACKHOLE(arr, sum);
}
return sum;
}
但这时即便是在循环外缓存了 length 也是没有用的,引擎没法预判数组的变化,当需要访问数组元素时会触发 bounds check ,从而照样要计算一遍 length 。所以缓存 length 是没有用的。
甚至,由于多了一个变量,底层的寄存器分配器每次循环还要多一次恢复这个变量。当然这个只有在大规模的情况下才会看出区别。
结尾
当然这篇文章也有局限性,仅仅讨论了 V8 引擎,也没有讨论访问 length 代价更高的 HTMLCollection 。但这已经足够说明两者差别不大,一般情况下我们不用再局限于缓存的写法,可以放开来按照自己喜欢的方式去写循环了。
【完】
原文:http://div.io/topic/966
缓存 Array.length 是老生常谈的小优化的更多相关文章
- check the element in the array occurs more than half of the array length
Learn this from stackflow. public class test { public static void main(String[] args) throws IOExcep ...
- [Bug]The maximum array length quota (16384) has been exceeded while reading XML data.
写在前面 在项目中,有客户反应无法正常加载组织结构树,弄了一个测试的程序,在日志中查看到如下信息: Error in deserializing body of reply message for o ...
- SPFA 小优化*2
/* bzoj 2763 SPFA小优化 循环队列+SLF 顺面改掉自己之前手打qeueu的坏毛病*/ #include<iostream> #include<cstring> ...
- Array.length vs Array.prototype.length
I found that both the Array Object and Array.prototype have the length property. I am confused on us ...
- 【转】The magic behind array length property
Developer deals with arrays every day. Being a collection, an important property to query is the num ...
- [MySQL5.6] 最近对group commit的小优化
[MySQL5.6] 最近对group commit的小优化 http://www.tuicool.com/articles/rEZr2q 最近花了一些时间在做MySQL Group Commit的优 ...
- Count and Say (Array Length Encoding) -- LeetCode
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
- SPFA的小优化
标签:闲扯 SPFA的小优化 1. 向队尾加入元素时,如果它比对首还优,就把把它直接和队首交换. 拿一个双端队列来实现 (手写 , head ,tail STLdeque亲测及其慢) 这个小优化其 ...
- Math.floor(Math.random() * array.length),splice
1.Math.floor(Math.random() * array.length) 返回长度内的索引 eg: changeLimit () { function getArrayItems(arr, ...
随机推荐
- SpringMVC的值传递
值的传递分为从页面传到到controller和从controller传递到页面,下面分别进行介绍: package com.springmvc.web; import java.util.Map; i ...
- flex与js相互调用
1.flex调用js方法 调用方法例如:ExternalInterface.call("UploadComplete",oldName,uidName,_dir+"/&q ...
- Single Number(JAVA)
Given an array of integers, every element appears twice except for one. Find that single one. Note: ...
- <转>maven发布第三方jar的一些问题
在创建maven中私有仓库过程中,需要发布一些第三方jar到nexus仓库,使用命令的是 deploy:deploy-file 有许多参数,具体可查看 http://maven.apache.org/ ...
- Mac系统杂项 (持续更新)
一.调整LaunchPad的图标显示列数和行数 .调整每一列显示图标数量.在我的电脑上(1366 * 768),每列7个个人觉得比较不错 defaults write com.apple.dock s ...
- Interaction with the camera or the photo library
As we said before, we need a delegate to deal with the user interaction with the camera or the photo ...
- 原生化:AnDevCon 2014 McVeigh 的主题演讲
作者:Jeff McVeigh(Intel) 基于(至少部分)NDK的原生安卓应用程序占现在前1000 强的 60% 以上.该增长的原因很简单:开发商需要为用户提供超卓的体验(包括灵敏的反应.与丰富的 ...
- hdu 5823 color II 状压dp
题目链接 给n个点 n<=18. 然后给出它们两两之间是否有边相连. 问你这个图的所有子集,最少要用多少种颜色来染色, 如果两个点相连, 那么这两个点不能染同样的颜色. 先预处理出所有的点独立集 ...
- 【转载】深入浅出http请求
转载链接:http://www.cnblogs.com/yin-jingyu/archive/2011/08/01/2123548.html HTTP(HyperText Transfer Proto ...
- vi全局替换方法
来自:http://blog.sina.com.cn/s/blog_736f1c59010136ry.html 1. 基本的替换 :s/vivian/sky/ 替换当前行第一个 vivian 为 sk ...