“Function calls are expensive” vs. “Keep functions small”

前端 未结 5 719
执笔经年
执笔经年 2020-12-12 23:45

On the one hand, I read or hear that \"function calls are expensive\" and that they impact efficiency (for example, on Nicholas Zakas\' Google tech talk).

On the oth

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 00:30

    Function calls are always expensive (especially in for cycles) and inlining doesn't happen as often as you may think

    The V8 engine that ships with Node.js (any version) is supposed to do inlining extensively but in practical terms this capability is greatly constrained.

    The following (trivial) snippet of code proves my point (Node 4.2.1 on Win10x64)

    "use strict";
    
    var a = function(val) {
      return val+1;
    }
    
    var b = function(val) {
      return val-1;
    }
    
    var c = function(val) {
      return val*2
    }
    
    var time = process.hrtime();
    
    for(var i = 0; i < 100000000; i++) {
      a(b(c(100)));
    }
    
    console.log("Elapsed time function calls: %j",process.hrtime(time)[1]/1e6);
    
    time = process.hrtime();
    var tmp;
    for(var i = 0; i < 100000000; i++) {
      tmp = 100*2 + 1 - 1;
    }
    
    console.log("Elapsed time NO function calls: %j",process.hrtime(time)[1]/1e6);
    

    Results

    Elapsed time function calls: 127.332373
    Elapsed time NO function calls: 104.917725
    

    +/- 20% performance drop

    One would have expected the V8 JIT compiler to inline those functions but in reality a, b or c could be called somewhere else in the code and are not good candidate for the low hanging fruit inlining approach you get with V8

    I've seen plenty of code (Java, Php, Node.js) having poor performance in production because of method or function call abuse: if you write your code Matryoshka style, run time performance will degrade linearly with the invocation stack size, despite looking conceptually clean.

提交回复
热议问题