GNU Compiler Optimization

I am not very good at compilers, but I know that they are complex and smart enough to optimize your code. Let's say I had a 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
 }

Will the GNU compiler be smart enough to realize that the length foodoes not change during this loop and replaces the call with the foo.length()correct value? Or could one call foo.length()for each comparison i?

+3
source share
4 answers

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

, length() , Loop Invariant Code Motion length() out .

, . - string, . , length() .

: , foo . - .

+6

Mystical, Kerrek , :

#include <string>
using namespace std;

int does_clang_love_me(string foo) {
    int j = 0;
    for (int i = 0; i < foo.length(); i++) {
        j++;
    }
    return j;
}

test.cpp :

$ clang++ -o test.o -Os -c test.cpp

-Os clang, . GCC , . , otool, mac. .

$ otool -tv test.o

test.o:
(__TEXT,__text) section
__Z16does_clang_love_meSs:
0000000000000000    pushq   %rbp
0000000000000001    movq    %rsp,%rbp
0000000000000004    movq    (%rdi),%rax
0000000000000007    movq    0xe8(%rax),%rcx
000000000000000b    xorl    %eax,%eax
000000000000000d    testq   %rcx,%rcx
0000000000000010    je  0x0000001e
0000000000000012    cmpq    $0x01,%rcx
0000000000000016    movl    $0x00000001,%eax
000000000000001b    cmoval  %ecx,%eax
000000000000001e    popq    %rbp
000000000000001f    ret

Mystical; .

+7

, , length() . , , , .

, . , .

- :

for (unsigned int i = 0, end = s.length(); i != end; ++i)

, for (char & c : s) .

+2

, , gcc . " ". foo.length() , , . , 9.5 ( ), , , . Standford: http://suif.stanford.edu/~courses/cs243/lectures/l5.pdf. , .

0

All Articles