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!
If
array[index]isnull, the second bit of code, trying to access members will throw aNullReferenceException.This can’t happen with the first bit of code, where you are assigning a newly constructed
FOO_Dataobject.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.