Viet Viet - 1 year ago 84
C++ Question

Why are new()/delete() slower than malloc()/free()?

Why new()/delete() is slower than malloc()/free()?


Thanks for the answers so far. Please kindly point out specifications of standard C++ implementation of new() and delete() if you have them thanks!

sbi sbi
Answer Source

Look at this piece of C code:

struct data* pd = malloc(sizeof(struct data));

The new operator in C++ is essentially doing what the above piece of code does. That's why it is slower than malloc().

Likewise with delete. It's doing the equivalent of this:


If the constructors and destructors are empty (like for built-ins), new and delete shouldn't be slower than malloc() and free() are. (If they are, it's often due to the fact that common implementations call malloc()/free() under the hood, so they are a wrapper around them. Wrapping costs. Also, there might be code that needs to find out that no constructors/destructors are to be called. That would cost, too.)

Edit To answer your additional question:

new and delete aren't functions, they are operators. This: new data() is called a new expression. It does two things. First it calls the operator new, then it initializes the object, usually by invoking the appropriate constructor. (I say "usually" because built-ins don't have constructors. But a new expression involving a built-in works the same nevertheless.)

You can manipulate both of these phases. You can create your own constructors to manipulate initialization of your types and you can overload operator new (even with several overloads having different additional arguments and also specifically for each class, if you want) in order to manipulate allocation of free storage. If you don't implement your own operator new, the version from the standard library is used. A common implementation of this calls malloc().

Likewise, if you write delete pd, called a delete expression, two things happen: depending on pd, the object is de-initialized, usually by calling its destructor, then the memory is released by calling the appropriate operator delete.

Again, you can manipulate both phase, by writing your own destructor, and by writing your own version of operator delete. (The version of operator delete that comes with your standard library is often implemented to call free().)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download