有哪些关键字/工具可以帮助编译器优化

发布于 2024-11-25 03:11:29 字数 784 浏览 4 评论 0原文

我们经常被告知这样的话,

如果您调用的方法的返回值不变,请将其从循环中取出。

例如,在编写如下代码时:

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

我想知道您是否可以告诉编译器,给定相同的输入(和对象实例),您将获得相同的输出,因此它会知道它可以将其移出循环作为优化过程。

有这样的事情存在吗?也许类似于 ?或者他们已经可以做这种事情了吗?

编译器是否可以推断出一个方法本身就是一个纯函数

我可以在 C# 中使用什么东西来使编译器执行更多的优化吗? 是的,我知道过早优化。我问这个问题主要是出于好奇,但如果确实存在类似上面的东西,一旦标记了该方法,它就会“免费”。

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:

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 or ? 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静谧 2024-12-02 03:11:29

Microsoft FxCop 检测到一些效率问题,这是 平台SDK

它检测到的 18 个性能相关问题的列表位于此处。

但是,它不会检测您提到的具体示例。

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.

朦胧时间 2024-12-02 03:11:29

这可能不是您想要的,但您也许可以重写循环,以便仅显式调用昂贵的方法一次(在循环开始时):

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

这也可以写为:

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

另一种明显的方法就是只使用一个临时变量(这意味着你自己进行优化):

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

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文