tags:

views:

67

answers:

1

I am confused here. Which is lighter object? is orgWithNullImageCollection or orgWithImageCollection ? in the below code. Or is it lighter object concept at all. Please find the code snippet below for the reference.


class Orgnization
{
    public Collection ImageCollection { get; set; }
}

Organization orgWithNullImageCollection = new Organization();
org.ImageCollection = null;


Collection imageCollection = new Collection();
// Adding 100 images to imageCollection

Organization orgWithImageCollection = new Organization();
org.ImageCollection = imageCollection;


Is there any difference in performance if I pass these two objects to any other methods? ie passing orgWithNullImageCollection over orgWithImageCollection ?

I believe that, it won't make any difference whether ImageCollection property of Organization objects points to something or not.

Please clarify.

+9  A: 

You never pass objects in C# - only ever values of value types, or references. In this case, you'd be passing a reference as you're dealing with a class. The reference will be the same size (4 or 8 bytes) regardless of the contents of the object it refers to (if any).

In this case, both objects will be the same size - it's just that one of them will have a null reference where the other has a reference to a collection.

As such you could regard the one with the collection as "heavier" in that are two objects involved instead of one. The extra collection will take memory, obviously - whereas a null reference doesn't refer to any object, so only the size of the null reference itself is required.

For more information, see my article about value types and reference types and argument passing.

Jon Skeet