What is the cost of a function call?

后端 未结 15 641
天命终不由人
天命终不由人 2020-12-12 22:34

Compared to

  • Simple memory access
  • Disk access
  • Memory access on another computer(on the same network)
  • Disk access on another computer
相关标签:
15条回答
  • 2020-12-12 23:05

    Function call is actually a copy of parameters onto the stack (multiple memory access), register save, the actual code execution, and finally result copy and and registers restore (the registers save/restore depend on the system).

    So.. speaking relatively:

    • Function call > Simple memory access.
    • Function call << Disk access - compared with memory it can be hundreds of times more expensive.
    • Function call << Memory access on another computer - the network bandwidth and protocol are the grand time killers here.
    • Function call <<< Disk access on another computer - all of the above and more :)
    0 讨论(0)
  • 2020-12-12 23:07

    If the function is inlined at compile time, the cost of the function becomes equivelant to 0.

    0 of course being, what you would have gotten by not having a function call, ie: inlined it yourself.

    This of course sounds excessively obvious when I write it like that.

    0 讨论(0)
  • 2020-12-12 23:08

    In general, a function call is going to be slightly slower than memory access since it in fact has to do multiple memory accesses to perform the call. For example, multiple pushes and pops of the stack are required for most function calls using __stdcall on x86. But if your memory access is to a page that isn't even in the L2 cache, the function call can be much faster if the destination and the stack are all in the CPU's memory caches.

    For everything else, a function call is many (many) magnitudes faster.

    0 讨论(0)
  • 2020-12-12 23:08

    Only memory access is faster than a function call.

    But the call can be avoided if compiler with inline optimization (for GCC compiler(s) and not only it is activated when using level 3 of optimization (-O3) ).

    0 讨论(0)
  • 2020-12-12 23:10

    The cost of a function call depends on the architecture. x86 is considerably slower (a few clocks plus a clock or so per function argument) while 64-bit is much less because most function arguments are passed in registers instead of on the stack.

    0 讨论(0)
  • 2020-12-12 23:12

    A function call usually involves merely a couple of memory copies (often into registers, so they should not take up much time) and then a jump operation. This will be slower than a memory access, but faster than any of the other operations mentioned above, because they require communication with other hardware. The same should usually hold true on any OS/language combination.

    0 讨论(0)
提交回复
热议问题