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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With