Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: delete vs. free and performance

  1. Consider:

    char *p=NULL; free(p) // or delete p; 

    What will happen if I use free and delete on p?

  2. If a program takes a long time to execute, say 10 minutes, is there any way to reduce its running time to 5 minutes?

like image 471
user41522 Avatar asked Nov 30 '08 13:11

user41522


People also ask

Which is faster free or delete?

The delete() operator is faster than the free() function.

What is the difference between free () and delete?

free() is a C library function that can also be used in C++, while “delete” is a C++ keyword. free() frees memory but doesn't call Destructor of a class whereas “delete” frees the memory and also calls the Destructor of the class.

What will happen if you malloc and free instead of delete?

If we allocate memory using malloc, it should be deleted using free. If we allocate memory using new, it should be deleted using delete. Now, in order to check what happens if we do the reverse, I wrote a small code.


1 Answers

Some performance notes about new/delete and malloc/free:

malloc and free do not call the constructor and deconstructor, respectively. This means your classes won't get initalized or deinitialized automatically, which could be bad (e.g. uninitalized pointers)! This doesn't matter for POD data types like char and double, though, since they don't really have a ctor.

new and delete do call the constructor and deconstructor. This means your class instances are initalized and deinitialized automatically. However, normally there's a performance hit (compared to plain allocation), but that's for the better.

I suggest staying consistent with new/malloc usage unless you have a reason (e.g. realloc). This way, you have less dependencies, reducing your code size and load time (only by a smidgin, though). Also, you won't mess up by free'ing something allocated with new, or deleting something allocated with malloc. (This will most likely cause a crash!)

like image 153
strager Avatar answered Oct 13 '22 17:10

strager