Which is faster: Stack allocation or Heap allocation

前端 未结 23 1828
悲&欢浪女
悲&欢浪女 2020-11-22 07:40

This question may sound fairly elementary, but this is a debate I had with another developer I work with.

I was taking care to stack allocate things where I could, i

23条回答
  •  鱼传尺愫
    2020-11-22 08:02

    I'd like to say actually code generate by GCC (I remember VS also) doesn't have overhead to do stack allocation.

    Say for following function:

      int f(int i)
      {
          if (i > 0)
          {   
              int array[1000];
          }   
      }
    

    Following is the code generate:

      __Z1fi:
      Leh_func_begin1:
          pushq   %rbp
      Ltmp0:
          movq    %rsp, %rbp
      Ltmp1:
          subq    $**3880**, %rsp <--- here we have the array allocated, even the if doesn't excited.
      Ltmp2:
          movl    %edi, -4(%rbp)
          movl    -8(%rbp), %eax
          addq    $3880, %rsp
          popq    %rbp
          ret 
      Leh_func_end1:
    

    So whatevery how much local variable you have (even inside if or switch), just the 3880 will change to another value. Unless you didn't have local variable, this instruction just need to execute. So allocate local variable doesn't have overhead.

提交回复
热议问题