C # - do you need to shorten your search chains like in javascript?

I have a class that has a public property. In one function, I refer to this property about 30-40 times.

this.MyProp; 

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

  string myProp = this.MyProp; 

After that - in the function, I shortened the search chains ... so I only need to reference myProp, not this.MyProp.

In JavaScript, this search reduction really improves performance. Would it be better / worse in C #? Because, obviously, I also need to create another local string variable.

+4
source share
6 answers

In terms of pure performance, it depends on what the property does. If the MyProp tag simply returns a private field, the overhead is completely irrelevant. In fact, if you are clearly not doing something meaningful, like a huge census or a call to a database, this has nothing to do. The concern about this is micro-micro optimization.

It is important to note the purpose of the properties, although this means forcing access to the value using an encapsulated procedure to ensure consistency. If you try to get around this, you put your code at a greater risk of errors.

From the comments of @DavidAndres:

By convention, properties usually should not do anything significant in a getter or setter. Therefore, I would say that it does not matter if you just check through the reflector or the documentation or look at your own code that the property is behaving well. Handling situations where the value clearly needs to be localized should be the edge after it has been verified that it is necessary.

Change To be clear, I do not recommend that you avoid local values ​​at all for any reason. As @Guffa notes, the impact is trivial anyway. I point out that properties are usually properties for some reason, and access to the value should go through the default property.

+11
source

Do not be afraid to declare local variables, it is almost free. On a 32-bit system, a string variable will use four bytes of stack space. The stack frame, where local variables are distributed, is always created, therefore, additional execution time is not required to allocate a variable.

However, whether or not to use a local variable is more likely based on a more correct situation. Unless you have a loop in which you use a value about a thousand times or more, the performance difference is unlikely to be even measurable.

(This, of course, is based on the assumption that the property is correctly implemented, so you should not read it.)

+1
source

You usually do not need this. to reference a property or field in the same class. I use it only in case of name conflict. Microsoft naming conventions avoid conflicts, so I don't use it. :)

As an aside, if you have one method that refers to a property 30–40 times, you probably have a Long Method smell.

EDITOR: I was not going to start a religious war for using "this." ( See Prefixing your instance variable with “this in java? ). In our company, we prefix fields with underscores (this is another hot topic); plus our (otherwise non-Hungarian) naming conventions make it very obvious that is a property. With ReSharper we can even do something like color code options in different ways. Personally, I find "this" as noise and follow the recommendations of ReSharper to remove it.

In the end, I agree with the answer. Although I value readability greatly if you cannot quickly and easily determine what this method does (whether it is or not), it is probably too long.

0
source

For a simple function and regular properties, this should not bother you. This is a really good question for lambda expressions , although a quick test shows that in this case it can be useful if you have a lot of property references (this is similar to what was done here ):

 class Program { public static int Property { get; set; } static void Main(string[] args) { Property = 3; int mainVar = Property; for (int run = 0; run < 5; run++) { Stopwatch s = new Stopwatch(); Action useProperty = () => { double res; for (int counter = 0; counter < 10000000; counter++) res = Math.Cos(Property); }; s.Start(); useProperty(); Console.WriteLine("Property Direct : {0}", s.Elapsed); s.Reset(); Action useMainVar = () => { double res; for (int counter = 0; counter < 10000000; counter++) res = Math.Cos(mainVar); }; s.Start(); useProperty(); Console.WriteLine("Variable from Main: {0}", s.Elapsed); s.Reset(); Action useLocalVariable = () => { int j = Property; double res; for (int counter = 0; counter < 10000000; counter++) res = Math.Cos(j); }; s.Start(); useLocalVariable(); Console.WriteLine("Lambda Local : {0}", s.Elapsed); Console.WriteLine(); } Console.ReadKey(); } } 

Result:

  Property Direct: 00: 00: 00.6410370
 Variable from Main: 00: 00: 00.6265704
 Lambda Local: 00: 00: 00.2793338

 Property Direct: 00: 00: 00.6380671
 Variable from Main: 00: 00: 00.6354271
 Lambda Local: 00: 00: 00.2798229

 Property Direct: 00: 00: 00.6337640
 Variable from Main: 00: 00: 00.6280359
 Lambda Local: 00: 00: 00.2809130

 Property Direct: 00: 00: 00.6286821
 Variable from Main: 00: 00: 00.6254493
 Lambda Local: 00: 00: 00.2813175

 Property Direct: 00: 00: 00.6279096
 Variable from Main: 00: 00: 00.6282695
 Lambda Local: 00: 00: 00.2783485
0
source

Most of the smaller properties are automatically configured by JIT, so there is not much performance gain.

For non-trivial properties, you really save time by shortening the search chain. The optimizer is not allowed to remove redundant calls because it cannot determine whether they have side effects or not, otherwise it will change the semantics of the program.

There is one exception in which you do not have to store the property value in local:

 for (int i=0; i<myArray.Length; i++) { /* do something with myArray[i] */ } 

This pattern is recognized by JIT and it will automatically remove the array access restriction test.

But if you do this:

 int len = myArray.Length; for (int i=0; i<len; i++) { /* do something with myArray[i] */ } 

Then the bounds test cannot be deleted, because the optimizer can never be sure that the len variable can be released.

So, think twice before "optimizing."

0
source

I did a performance calculation, however its tiny, but every tiny bit added can be a huge gain compared to processor cycles, as you execute code 100 times in time on a web server, in network activity, etc.

C # Local statistics of variable caching , you can also download the code and play with it.

-one
source

All Articles