可以编译器优化elminate函数在一个for循环的条件重复调用吗? [英] Can compiler optimization elminate a function repeatedly called in a for-loop's conditional?

查看:203
本文介绍了可以编译器优化elminate函数在一个for循环的条件重复调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于哈希函数(我是一个中级CS学生),并遇到了这个:

I was reading about hash functions (i'm an intermediate CS student) and came across this:

int hash (const string & key, int tableSize) {
    int hasVal = 0;

    for (int i = 0; i < key.length(); i++)
        hashVal = 37 * hashVal + key[i];

    .....
    return hashVal;
}



我在看这个代码,注意到如果在for-loop而不是调用key.length()每次我们改为这样:

I was looking at this code and noticed that it would be faster if in the for-loop instead of calling key.length() each time we instead did this:

int n = key.length();
for (int i = 0; i < n; i++)



,因为这是一个明显的方式稍微提高性能编译器自动为我们这样做?我还不知道编译器,但我很好奇这个问题的答案。当编写代码以使用较少的操作时,人们经常指出,我做的事情通常已经由编译器为我完成了,所以我浪费我的时间,但做诸如内联函数之类的事情。我关心这个,因为我编程的游戏,物理处理需要有效率,所以不要感到笨重。

My question is, since this is such an obvious way to slightly improve performance does the compiler automatically do this for us? I don't yet know much about compilers but I was curious as to the answer of this question. When writing code to use less operations people have often pointed out that the things that I do are often already done for me by the compiler so I'm wasting my time but doing things such as inline functions. I care about this because I am programming a game where physics processing needs to be efficient so that things don't feel clunky.

推荐答案

简短答案:有时可以...

Short answer: It can sometimes...

Long答案:

如果编译器可以基于循环本身确定key.length()是一个常量值,那么它将能够优化调用。这反过来取决于使用的类的定义(在这种情况下 string ,我们可以期望是写得很好)。它还依赖于编译器的理解,循环不会以改变 key.length() c>。

If the compiler can determine that key.length() is a "constant" value based on the loop itself, then it will be able to optimise out the call. This in turn depends on the definition of the class used (in this case string, which we can expect is "well written"). It also relies on the compiler understanding that the loop isn't altering the key in a way that alters key.length().

此工作的关键元素是函数 inline (或是一个模板函数, inline 是必需的,以允许它在不同的编译单元中被多次包含 - 或者在同一源文件中可用),源代码在编译单元包括的头文件中。

Key elements for this to ever work is that the function is inline (or is a template function, inline is required to allow it to be included multiple times in different compile units - or available within the same source file) and the source code is in a header file included by the compile unit.

当然,C ++标准中没有要求编译器这样做。它完全符合标准的每次调用功能。

And of course, there is no requirement in the C++ standard that the compiler does this. It is perfectly within the standard compliance to call the function every time.

这篇关于可以编译器优化elminate函数在一个for循环的条件重复调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆