Nodejs优化的小小黑科技

先来玩个小游戏,大家来找茬! 从下面给出的两段代码中,找出不同的地方。

片段一 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.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的值来提高执行效率

「原文链接」

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值