Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - do you need to shorten lookup chains, like in JavaScript?

Tags:

c#

.net

I have a class that has a public property. In a single function I refer to this property around 30-40 times.

  this.MyProp; 

Would it be better to define a local variable in the function?,

 string myProp = this.MyProp;

After doing this - in the function I've shortened the lookup chains... so I only have to refer to myProp, rather than this.MyProp.

In JavaScript this shortening of lookups really improves performance. Would it be better / worse in C#? Because obviously, I've also needed to create another local string variable.

like image 592
JL. Avatar asked Dec 23 '22 09:12

JL.


2 Answers

From a pure performance perspective, it depends on what the property is doing. If the MyProp getter just returns a private field, the overhead is totally inconsequential. In fact, unless you're obviously doing something significant like some huge enumeration or calling into a database, it's of no concern. Worrying about this is micro-micro optimization.

It's important to note the purpose of properties though, which is to force access to a value through an encapsulated routine to ensure consistency. If you try to bypass that, you're exposing your code to greater risk for bugs.

From @DavidAndres comments:

According to convention, properties should typically not do anything substantial in the getter or setter. So I would say it's of no concern if you simply verify, via reflector or documentation or looking at your own code, that the property behaves well. Handling the situations where the value clearly does need to be localized should be an edge case, after it's been verified that it is necessary.

Edit: To be clear, I am not recommending you generally avoid local values for any performance reason. As @Guffa notes the impact is trivial either way. I am pointing out that properties are usually properties for a reason, and access to the value should go through the property by default.

like image 125
Rex M Avatar answered Jan 26 '23 00:01

Rex M


Don't be afraid to declare local variables, it's almost free. On a 32 bit system the string variable will use four bytes of stack space. The stack frame where the local variables are allocated is always created, so it takes no extra execution time to allocate the variable.

However, whether you should use a local variable or not should rather be based on what's more correct in the situation. Unless you have a loop where you use the value something like a thousand times or more, the performance difference will hardly even be measurable.

(This is of course based on the assumption that the propery is properly implemented so that it isn't expensive to read.)

like image 21
Guffa Avatar answered Jan 25 '23 22:01

Guffa