Nodejs優化的小小黑科技

先來玩個小遊戲,你們來找茬! 從下面給出的兩段代碼中,找出不一樣的地方。

片斷一 example1.jsjavascript

'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.jsjava

'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.82s減小到了0.67side

解開謎底

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

建議

  • 若是要循環調用一個函數,儘可能讓函數字符不要超過600
  • 能夠經過修改默認的max-inlined-source-size的值來提升執行效率

「原文連接」

相關文章
相關標籤/搜索