Nullptr Removal - Performance Overhead?

The operator itself removes the checks if the pointer is nullptr. Is there any overhead when calling delete on nullptr without checking it yourself?

delete ptr; 

or

 if (ptr != nullptr) delete ptr; 

Which of the above is faster if ptr is nullptr?

+8
c ++
source share
4 answers

As usual, it depends on the compiler.

I use MSVC, which compiles both of these lines exactly in the same code.

The rules say that if the pointer is null, the deletion does not work. Therefore, if you do not, the compiler should in any case.

+18
source share

This is finally the case of over-optimization. On any modern processor, the difference is a few nanoseconds.

By performing verification, the code avoids the overhead of the call (to the library deletion procedure). In 99% of cases, a little extra complexity of the source code (curly braces, potential spelling of typos != Etc.) is a bigger problem than extra execution time.

+2
source share

No, there is no overhead unless you check if ptr nullptr .

If you do the check manually, the same check is performed twice, although this is insignificant, compared to the cost of the system call, you can expect if ptr not null.

+2
source share

Which of the above is faster if ptr is nullptr?

Assuming your check is not optimized, the top one will be faster. If it is optimized, none of them will be faster. Leave it to the compiler.

+2
source share

All Articles