Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

EDIT:

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

like image 782
Viet Avatar asked Apr 03 '10 07:04

Viet


2 Answers

Look at this piece of C code:

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

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:

deinit_data(pd);
free(pd);

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().)

like image 164
sbi Avatar answered Sep 28 '22 16:09

sbi


new and delete are dealing with construction/destruction for which part of their work is the effectively calling malloc() and free() - malloc() and free() are raw memory allocation/deallocation.

like image 24
Lee Avatar answered Sep 28 '22 17:09

Lee