Are arrow functions faster (more performant, lighter) than ordinary standalone function declaration in v8?

后端 未结 5 1560
太阳男子
太阳男子 2020-12-01 04:42

I am asking this question because I and my colleague have a dispute on coding style because he prefers arrows function declaration:

const sum = (a, b) =>          


        
5条回答
  •  既然无缘
    2020-12-01 05:46

    There are two examples for nodejs:

    function testFat(a, b) {
        return a + b;
    }
    
    let testArrow = (a, b) => a + b;
    
    let t1 = process.hrtime();
    let tmp1 = 0;
    for (let i = 0; i < 1000000000; ++i) {
        tmp1 = testFat(tmp1, i);
    }
    var fatTime = process.hrtime(t1);
    console.log('fat', fatTime);
    
    let t2 = process.hrtime();
    let tmp2 = 0;
    for (let i = 0; i < 1000000000; ++i) {
        tmp2 = testArrow(tmp2, i);
    }
    var arrowTime = process.hrtime(t2);
    console.log('arrow', arrowTime);
    
    function testFat() {
        return 0;
    }
    
    let testArrow = () => 0;
    
    let t1 = process.hrtime();
    for (let i = 0; i < 1000000000; ++i) {
        testFat();
    }
    var fatTime = process.hrtime(t1);
    console.log('fat', fatTime);
    
    let t2 = process.hrtime();
    for (let i = 0; i < 1000000000; ++i) {
        testArrow();
    }
    var arrowTime = process.hrtime(t2);
    console.log('arrow', arrowTime);```
    

    Results are:

    bash-3.2$ node test_plus_i.js

    fat [ 0, 931986419 ]

    arrow [ 0, 960479009 ]

    bash-3.2$ node test_zero.js

    fat [ 0, 479557888 ]

    arrow [ 0, 478563661 ]

    bash-3.2$ node --version

    v12.8.0

    bash-3.2$

    So you can see that there is no difference in function call overhead.

提交回复
热议问题