niemiro
niemiro

Reputation: 1838

Which of these two is more efficient?

I know this is a little bit hypothetical, because I am not looping this, it only occurs once or twice in a program run, and so it will only be a completely unnoticable amount of time, but I want to know if one of these is better than the other, or if it doesn't matter at all, because the optimiser will optimise away the worse code.

I have this class:

class FOO_Data
{
    private string description, url;
    private bool editable;

    public FOO_Data(string description, string url, bool editable)
    {
        this.description = description;
        this.url = url;
        this.editable = editable;
    }

    public string Description { get { return description; } set { description = value; } }
    public string URL { get { return url; } set { url = value; } }
    public bool Editable { get { return editable; } set { editable = value; } }
} 

At some other point in my code, I need to edit an instance of this class in an array of this class.

Which one is better? This one:

array[index] = new FOO_Data(data.Description, data.URL, System.Convert.ToBoolean(data.Editable));

or this one:

array[index].Description = data.Description;
array[index].Editable = Convert.ToBoolean(data.Editable);
array[index].URL = data.URL;

I would tend towards the first, but I am not very sure. I would appreciate any insight you could offer.

Thanks a lot!

Upvotes: 1

Views: 122

Answers (3)

Saeed Amiri
Saeed Amiri

Reputation: 22565

first of all, If you work on .Net 3 or newer you can use auto implemented properties:

public string Description { get; set;}

Instead of properties with backing field.

also about which one is better, i think It's syntactic sugar, but I'll prefer first approach, because encapsulates initialization, also In your second approach possibility of null exception exists. in fact you shouldn't think about bit optimization.

Upvotes: 3

Jason Meckley
Jason Meckley

Reputation: 7591

I would opt for the second approach, slightly altered.

var foo = array[index];
if(foo == null)
{
    foo = new Foo_Data();
    array[index] = foo;
}
foo.Description = data.Description;
foo.Editable = ...
...

Upvotes: 2

Oded
Oded

Reputation: 499382

If array[index] is null, the second bit of code, trying to access members will throw a NullReferenceException.

This can't happen with the first bit of code, where you are assigning a newly constructed FOO_Data object.

In terms of performance, you are unlikely to see any difference if the array is indeed fully populated as object creation is a very light process.

Upvotes: 3

Related Questions