C++: delete vs. free and performance

后端 未结 7 1354
天命终不由人
天命终不由人 2021-01-30 11:07
  1. Consider:

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

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

7条回答
  •  不要未来只要你来
    2021-01-30 11:34

    Nothing will happen if you call free with a NULL parameter, or delete with an NULL operand. Both are defined to accept NULL and perform no action.

    There are any number of thing you can change in C++ code which can affect how fast it runs. Often the most useful (in approximate order) are:

    • Use good algorithms. This is a big topic, but for example, I recently halved the running time of a bit of code by using a std::vector instead of a std::list, in a case where elements were being added and removed only at the end.
    • Avoid repeating long calculations.
    • Avoid creating and copying objects unnecessarily (but anything which happens less than 10 million times per minute won't make any significant difference, unless you're handling something really big, like a vector of 10 million items).
    • Compile with optimisation.
    • Mark commonly-used functions (again, anything called more than 100 million times in your 10 minute runtime), as inline.

    Having said that, divideandconquer is absolutely right - you can't effectively speed your program up unless you know what it spends its time doing. Sometimes this can be guessed correctly when you know how the code works, other times it's very surprising. So it's best to profile. Even if you can't profile the code to see exactly where the time is spent, if you measure what effect your changes have you can often figure it out eventually.

提交回复
热议问题