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?

Best Solution

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!)