GNU编译器优化 [英] GNU Compiler optimization

查看:174
本文介绍了GNU编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解编译器,但知道他们是复杂和聪明的,以优化你的代码。说我有这样的代码:

I don't know much about compilers, but know they are complicated and smart enough to optimize your code. Say I had code that looked like this:

 string foo = "bar";
 for(int i = 0; i < foo.length(); i++){
     //some code that does not modify the length of foo
 }

GNU编译器能够聪明地实现 foo 在这个循环的过程中不改变,并用适当的值替换 foo.length()调用?或者每次 i 比较会调用 foo.length()

Would the GNU compiler be smart enough to realize that the length of foo does not change over the course of this loop and replace the foo.length() call with the proper value? Or would foo.length() be called for every i comparison?

推荐答案

确定的唯一方法是尝试并查看程序集。

The only way to know for sure is to try it and take a look at the assembly.

我的猜测是,如果调用 length()是内联的,那么循环不变代码运动将提升 length()的内部,

My guess is that if the call to length() is inlined, then Loop Invariant Code Motion will hoist the internals of length() out of the loop and replace it with a single variable.

作为第二个想法,这可能是没有意义的。字符串的大小可能只是在 string 类中的一个简单字段 - 它在堆栈上。因此,只是内联对 length()的调用已经具有减少对简单变量访问的调用的效果。

As a second thought, this might even be moot. The size of a string is probably just a simple field in the string class - which is on the stack. So just inlining the call to length() will already have the effect of reducing the call to a simple variable access.

EDIT:
在后一种情况下,无论是否在 foo 循环。获取字符串的长度已经只是一个变量访问。

EDIT : In this latter case, it doesn't even matter whether or not the length of foo is modified inside the loop. Getting the length of a string is already just a variable access.

这篇关于GNU编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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