Is declaration of variables expensive?

前端 未结 12 969
长情又很酷
长情又很酷 2021-02-01 00:39

While coding in C, I came across the below situation.

int function ()
{
  if (!somecondition) return false;

  internalStructure  *str1;
  internalStructure *str         


        
12条回答
  •  醉梦人生
    2021-02-01 01:04

    If it actually mattered the only way to avoid allocating the variables is likely to be:

    int function_unchecked();
    
    int function ()
    {
      if (!someGlobalValue) return false;
      return function_unchecked();
    }
    
    int function_unchecked() {
      internalStructure  *str1;
      internalStructure *str2;
      char *dataPointer;
      float xyz;
    
      /* do something here with the above local variables */    
    }
    

    But in practice I think you'll find no performance benefit. If anything a minuscule overhead.

    Of course if you were coding C++ and some of those local variables had non-trivial constructors you would probably need to place them after the check. But even then I don't think it would help to split the function.

提交回复
热议问题