-4

I wanna know the performance difference b/w

sample *s = new sample();

and

sample s;

where sample is a class.

sree teja
  • 27
  • 1
  • 7
  • The answer is that it depends on the compiler, platform, compiler settings, size of the class, your heap, and in *difference* percentage-wise, the constructor of the class. It's generally not worth worrying about. If it is, You have to test it. – zzxyz Oct 21 '17 at 01:24
  • 3
    If either of those two lines is a performance bottleneck in your program you have a problem. Your example also doesn't include a static, as in the C++ keyword, anything. – Retired Ninja Oct 21 '17 at 01:28
  • @RetiredNinja I just started learning c++ so sorry if the question doesn't make sense,. and by the way, I was speaking about static memory allocation where the memory is allocated at the compile time and at the stack memory location, whereas in dynamic memory allocation the memory is allocated at runtime and at the heap memory location so is there any performance difference for the two? – sree teja Oct 21 '17 at 01:39
  • 1
    Stack allocation (not static) is almost always faster. Sometimes significantly, but you're talking nanoseconds (usually) on a desktop. – zzxyz Oct 21 '17 at 01:42
  • @sreeteja the solution to allocation performance problems is ALWAYS less allocations, not heap vs stack, and I've had it be an issue maybe three times in 20 years – zzxyz Oct 21 '17 at 01:57
  • 1
    Write readable program, if dynamic allocation makes your program simpler and more readable - use it. Then if it too slow run profiler and optimize parts that takes most time. – Slava Oct 21 '17 at 02:31

1 Answers1

0

The difference is that dynamic allocation is slower than the other storage durations. How much: It depends. The difference can be completely irrelevant (for example when the code is unused and compiler happens to be smart enough to optimize either away) or so important that dynamic allocation makes it impossible to guarantee a hard dead line.

A bigger problem with dynamic allocation, than the potential performance difference, is that unless you follow very strict conventions, it is very difficult to prove that your program doesn't leak memory, or that it has well defined behaviour.

eerorika
  • 181,943
  • 10
  • 144
  • 256