views:

139

answers:

3

Assume that we have 3 classes:

Place, Contact, PhoneNumber classes.

Under the Place class, I want to have a Contact class but it is better to keep PhoneNumber class under the Contact class. So in the Place class, it is more logical to reach the PhoneNumber by first getting the Contact object, then the PhoneNumber under the Contact object.

If I often need to get the PhoneNumber object from a place object, does keeping the PhoneNumber class under the Contact class (Place.Contact.PhoneNumber) instead of directly insert that object under the Place (Place.Contact) class cause any performance issues?

Why I ask this question is that these kind of scope issues have lots of performance effects in JavaScript. Does it worth to be so paranoiac about variable scope - performance relations in C#?

Thank you.

+3  A: 

In C# you won't see many performance issues around trivial* property getters and setters like this. However, without profiling, it is impossible to say if this will be a problem for you.

For most cases though, object graph constructions never create performance problems in C# like they can in JavaScript.


* Properties that simply return a reference to an existing object and have no additional logic.

Andrew Hare
+2  A: 

It will have an effect on performance, but won't cause issues. The just-in-time compiler compiles member accesses into direct pointer computations (having computed the layout of each class when the assembly was loaded), so member access is much faster in C# than it is in JavaScript.

Martin v. Löwis
+1  A: 

Unless this is the absolutely last stop on your list of things to try in order to make your program run slightly faster, and by "slightly" I actually mean "minuscule" in this case, then I would not worry about it.

To answer your question first, yes, this might impact code performance. The code to read ref.ref.prop will take slightly more code to do than ref.prop, obviously.

However, this will make very small impacts on code performance, and unless you're reading this property 2 levels down many many times in a loop, and doing not much else useful, the effect of having 1 or 2 levels on this particular scenario will be dwarfed by any other code you might be executing.

In any case, the general rule is to write the code the most obvious way, the most simple way, and the most understandable way, so that it is first and foremost easy to write and easy to maintain, which in the long term will lead to fewer bugs.

At some point, if your program has a performance problem, and you find out that this particular code is the piece of code that is taking the most time, at that moment, then, and only then, do you go in and try to optimize that code.

Lasse V. Karlsen