先来玩个小游戏,大家来找茬! 从下面给出的两段代码中,找出不同的地方。
片段一 example1.js
'use strict';
function add(x, y) {
// Addition is one of the four elementary,
// mathematical operation of arithmetic with the other being subtraction,
// multiplication and division. The addition of two whole numbers is the total
// amount of those quantitiy combined. For example in the picture on the right,
// there is a combination of three apples and two apples together making a total
// of 5 apples. This observation is equivalent to the mathematical expression
// "3 + 2 = 5"
// Besides counting fruit, addition can also represent combining other physical object.
return(x + y);
}
for(let i = 0; i < 500000000; i++) {
if (add(i, i++) < 5) {
//
}
}复制代码
片段二 example2.js
'use strict';
function add(x, y) {
// Addition is one of the four elementary,
// mathematical operation of arithmetic, with the other being subtractions,
// multiplications and divisions. The addition of two whole numbers is the total
// amount of those quantitiy combined. For example in the picture on the right,
// there is a combination of three apples and two apples together making a total
// of 5 apples. This observation is equivalent to the mathematical expression
// "3 + 2 = 5"
// Besides counting fruit, addition can also represent combining other physical object.
return(x + y);
}
for(let i = 0; i < 500000000; i++) {
if (add(i, i++) < 5) {
//
}
}复制代码
现在我们来分别执行它们,看看所消耗的时间,这里使用time命令 统计它们的耗时;
其实它们的差别就这样:
看我是不是和我一样一脸懵逼,明明一模一样的函数,为什么执行效率差距这么大,这里再给大家一个黑魔法(命令选项)
--max-inlined-source-size=xxx
// xxx 代码你要配置的数量复制代码
好吧,再看一张图:
发现了没有,执行时间从1.82
s减少到了0.67s
解开谜底
v8 optimizer (crankshaft) inlines the functions whose body length, including the comments, is less than 600 characters.
感谢评论区的指正:
v8优化器将包含注释的主体长度小于600(默认)个字符的内联函数。
v8 优化器会将那些函数体字符长度 (包含注释) 小于 600 个字符的函数,优化为内联函数。
于是 example1.js,的 add(i, i++) < 5 部分被优化为 (i + i++) < 5,减少了一次函数的调用,从而提高了运算速度
建议
- 如果要循环调用一个函数,尽量让函数字符不要超过600
- 可以通过修改默认的
max-inlined-source-size
的值来提高执行效率