片斷一 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
的值來提升執行效率