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]
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.
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.
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 = ...
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.