Nodejs優化的小小黑科技

東岸往事·發表於2016-12-12

先來玩個小遊戲,大家來找茬! 從下面給出的兩段程式碼中,找出不同的地方。

片段一 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命令 統計它們的耗時;

Nodejs優化的小小黑科技

其實它們的差別就這樣:

Nodejs優化的小小黑科技

看我是不是和我一樣一臉懵逼,明明一模一樣的函式,為什麼執行效率差距這麼大,這裡再給大家一個黑魔法(命令選項)

--max-inlined-source-size=xxx
// xxx 程式碼你要配置的數量複製程式碼

好吧,再看一張圖:

Nodejs優化的小小黑科技

發現了沒有,執行時間從1.82s減少到了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的值來提高執行效率

「原文連結」

相關文章