片断一 example1.js
javascript
'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
java
'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命令 统计它们的耗时;
node
其实它们的差异就这样:
express
看我是否是和我同样一脸懵逼,明明如出一辙的函数,为何执行效率差距这么大,这里再给你们一个黑魔法(命令选项)app
--max-inlined-source-size=xxx
// xxx 代码你要配置的数量复制代码
好吧,再看一张图:
less
发现了没有,执行时间从1.82
s减小到了0.67s
ide
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,减小了一次函数的调用,从而提升了运算速度ui
max-inlined-source-size
的值来提升执行效率