Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null pointer test performance

What is the performance of testing whether a reference-type variable in C# is a null-pointer (like if (x == null) ...) compared to testing for an integer being smaller than zero or even a bool being false?

Are there other issues know regarding such null-pointer tests, e.g. is garbadge produced?

I do hundred of these tests for every frame of a game and I was wondering if these could cause problems or could be implemented more efficiently?

like image 520
ares_games Avatar asked Jan 11 '13 12:01

ares_games


People also ask

What is the problem with null pointer?

Because a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash.

Is it safe to free a null pointer?

Checking just adds unnecessary clutter to your code, and free(NULL) is guaranteed to be safe. From section 7.20. 3.2/2 of the C99 standard: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.

Should you always check if a pointer is null?

It's good practice to check for null in function parameters and other places you may be dealing with pointers someone else is passing you. However, in your own code, you might have pointers you know will always be pointing to a valid object, so a null check is probably overkill... just use your common sense.

What is the importance of null pointer?

A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.


2 Answers

Nullity tests are likely to be equivalent to simple "equal to 0" tests. They're very, very cheap - mere hundreds per frame should be completely insignificant unless you've got a frame rate in the millions :)

You should profile your app to find out where the time is actually being spent - it's a lot more productive than just guessing. Ideally, you should also try to write some benchmarks so that you can not only measure current performance, but also notice if it gets significantly worse due to any particular change.

like image 187
Jon Skeet Avatar answered Oct 06 '22 09:10

Jon Skeet


Testing a value for null is not a complicated operation that needs type checking or something like that, and there is no memory allocation involved.

Disassembling the statement if (x == null) gives:

00000030  cmp         qword ptr [rsp+20h],0
00000036  jne         000000000000004A

I.e. the test is implemented as a simple integer comparison of the pointer value.

like image 29
Guffa Avatar answered Oct 06 '22 09:10

Guffa