开发者

What keywords/tools are there to help the compiler optimise

Often we're told things like,

If you're calling a method with a return value that doesn't change, take it out of the loop.

for example when writing code like:

开发者_Go百科for(int i=0; i < Instance.ExpensiveNonChangingMethod(); i++)
{
    // Stuff
}

I was wondering if you could some how tell the compiler that given the same inputs (and object instance) you would get the same outputs, so it would know it could move it out of the loop as part of the optimisation process.

Does anything like this exist? Perhaps something like code-contracts or spec#? Or can they already do this sort of thing?

Is it conceivable that the compiler could reason that a method is a pure function its-self?

Is there anything I can use in C# that will enable the compiler to perform more optimisation that it otherwise would? Yes i'm aware of premature optimisation. I'm asking mostly out of curiosity, but also if something like above did exist it would be 'for free' once the method was marked.


Some efficiency problems are detected by Microsoft FxCop, which is part of the Platform SDK.

The list of 18 performance related issues it detects is here.

It does not, however, detect the specific example you mentioned.


This is probably not what you're looking for, but you might be able to rewrite the loop so that the expensive method is only explicitly called once (at the start of the loop):

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

This can also be written as:

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

The other obvious approach is to just use a temporary variable (which means doing the optimization yourself):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜