Colton
Colton

Reputation: 1297

What happens behind the scenes when a value is set to null?

Lets say I have a populated array of objects.

 Resource[] list = new Resource[100000];

And once in a while, I would like to change an object in this list to a default value.

 Resource defaultResource = new Resource();

And later on, I would like to check if the item is default or not. So, I am wondering what the performance differences might be in setting the list object to a default value, versus setting a value to null.

 list[i] = defaultResource; /*versus*/ list[i] = null;

So really, I would like to know what goes on behind the scenes when a value is set to null versus setting it equal to something else.

Sorry if this is a dumb question!

Upvotes: 3

Views: 101

Answers (2)

jdphenix
jdphenix

Reputation: 15425

One possible option to consider for your scenario - you want the simplification of not having to write null checking code.

Consider subclassing your Resource class with a stub that represents a default value.

public class NoResource : Resource { }

// ... later

if (res is NoResource) { 
  // handle default value
}

This way, your code is still able to work with Resource objects as it expects to be able to, and you can optionally check for a default Resource easily.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

There's not much difference between setting a variable to an existing object vs. setting it to null. In both cases, the object that has been referenced by that variable before would get one step closer to becoming eligible for garbage collection, regardless of the new value stored in that variable being a null or a different object. The rest of the assignment goes in the same way, too: CLR does not maintain reference count, so nothing special needs to happen specifically at the point when the assignment is made.

It may be beneficial to store a default object in place of a null to avoid extensive null checking at runtime, though: doing so simplifies the code, and reduces the need for branching at runtime.

Upvotes: 4

Related Questions