Reputation: 3417
Consider the next piece of code
class foo {
public:
void f() {
char buffer[1024];
memset(buffer, NULL, 1024);
read_some_input_to_buffer(buffer, 1024);
}
};
class bar {
public:
void f() {
memset(_myPrivateBuffer, NULL, 1024);
read_some_input_to_buffer(_myPrivateBuffer, 1024);
}
private:
char _myPrivateBuffer[1024];
};
Will bar::f()
work faster than foo::f()
? As I see it, the buffer already exists in bar
, so the compiler won't allocate memory for it on the stack when the function is called? Or am I wrong and the memory is already allocated before foo::f()
is called as well?
Upvotes: 2
Views: 39
Reputation: 73366
is it faster if I store them in the class itself?
No.
so the compiler won't allocate memory for it on the stack
Allocating memory on the stack is equivalent to moving the stack pointer. And more important, stack is always hot, the memory you get is much more likely to be in cache than any far heap allocated memory. Read more in Which is faster: Stack allocation or Heap allocation.
PS: Be careful not to become a victim of premature optimization.
Upvotes: 1