What keywords / tools will help optimize the compiler

We are often told things like

If you call a method with a return value that does not change, remove it from the loop.

for example, when writing code like:

for(int i=0; i < Instance.ExpensiveNonChangingMethod(); i++) { // Stuff } 

I was wondering if you could somehow tell the compiler that given the same input (and the object instance) you would get the same outputs, so he would know that he could take it out of the loop as part of the optimization process.

Is there anything similar? Perhaps something like or ? Or can they already do such things?

Is it possible to assume that the compiler can assume that the method is a pure function itself?

Is there anything I can use in C # that allows the compiler to do a lot of optimization, which otherwise would be? Yes, I know about premature optimization. I ask mainly out of curiosity, but also, if something like the above existed, it would be "free" as soon as the method was noted.

+4
source share
2 answers

Some performance issues are discovered by Microsoft FxCop , which is part of the SDK Platform .

A list of 18 performance issues that he discovers is here .

However, it does not define the specific example you mentioned.

0
source

This is probably not what you are looking for, but you can rewrite the loop so that the expensive method is only explicitly called once (at the beginning of the loop):

 for (int i = Instance.ExpensiveNonChangingMethod(); i-- >= 0; ) { // Stuff } 

It can also be written as:

 int i = Instance.ExpensiveNonChangingMethod(); while (i-- >= 0) { // Stuff } 

Another obvious approach is to simply use a temporary variable (which means performing the optimization itself):

 int n = Instance.ExpensiveNonChangingMethod(); for (int i = 0; i < n; i++) { // Stuff } 
0
source

All Articles