3

I've seen a couple of posts about the differences between malloc and new and I do understand that.

However, none of those posts talks about performance, so I was wondering if there was any performance difference between those two or if the compiler essentially does the same thing.

For the sake of the comparison, let's suppose we're talking about primitive types here (Thank you Hans Passant).

Thank you in advance.

Community
  • 1
  • 1
OneMore
  • 1,139
  • 2
  • 9
  • 19

3 Answers3

8

You'd probably want to compare malloc() and free() with operator new() and operator delete() (and their array forms): This is how the memory is allocated independent from the construction of objects. The performance is likely to be very similar and it is quite likely that both approaches end up using the same memory pool: the C++ operators may be a thin wrappeer around malloc() and free() (but not the other way around: a user can safely implement operator new() and operator delete() in terms of malloc() and free()).

To determine the actual performance you'd obviously need to profile the two approaches in a reasonable way. Withouth having done so, I wouldn't expect much of a difference on most systems. Of course, the results will be specific to different systems.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
3

The only way to be sure is to time the various options on your compiler. There will be no hard and fast rule that applies to all compilers.

If you are talking about allocating an array of int or double, say, then for any decent implementation you should not be able to detect a performance difference.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
3

The answer will depend on the specific compiler, but I suspect most implementations of new simply call malloc under the covers. malloc will usually be slightly faster since it doesn't call any additional code (unlike new, which calls the object's constructor).

Peter Ruderman
  • 12,241
  • 1
  • 36
  • 58
  • 1
    When the constructor does something really CPU-intensive, malloc would even be *a lot* faster. But usually you have a reason to do all that stuff in the constructor, and when you haven't you could add another constructor which doesn't. But seriously, malloc should only be used for POD types, never for objects, because the constructor is usually there for a reason. – Philipp Dec 30 '12 at 19:41