Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large buffers vs Large static buffers, is there an advantage?

Consider the following code.

Is DoSomething1() faster then DoSomething2() in a 1000 consecutive executions? I would assume that if I where to call DoSomething1() it 1000 times it would be faster then calling DoSomething2() it 1000 times.

Is there any disadvantage to making all my large buffers static?

#define MAX_BUFFER_LENGTH 1024*5 
void DoSomething1()
{
    static char buf[MAX_BUFFER_LENGTH] ; 
    memset( buf, 0, MAX_BUFFER_LENGTH );
}

void DoSomething2()
{
    char buf[MAX_BUFFER_LENGTH] ; 
    memset( buf, 0, MAX_BUFFER_LENGTH );
}

Thank you for your time.

like image 979
Steven Smethurst Avatar asked Nov 29 '22 20:11

Steven Smethurst


1 Answers

Disadvantage of static buffers:

  • If you need to be thread safe then using static buffers probably isn't a good idea.
  • Memory won't be freed until the end of your program hence making your memory consumption higher.

Advantages of static buffers:

  • There are less allocations with static buffers. You don't need to allocate on the stack each time.
  • With a static buffer, there is less chance of a stack overflow from too high of an allocation.
like image 102
Brian R. Bondy Avatar answered Dec 01 '22 09:12

Brian R. Bondy