Where to define a constant with one shot for the most efficient code?

Which option is most effective and why? Or will they be optimized for the same code?

char inplace(int i) {
    // [some check if 0<=i<=2 here]
    return "azS"[i];
}

char infunc(int i) {
    const char s[] = "azS";
    // [some check if 0<=i<sizeof(s)/sizeof(s[0])-1 here]
    return s[i];
}

const char s[] = "azS";
char inglobals(int i) {
    // [some check if 0<=i<sizeof(s)/sizeof(s[0])-1 here]
    return s[i];
}

Please do not say that premature optimization of evil is just an irresistible curiosity inherent in the born C ++ 'er;)

+5
source share
2 answers

I just compiled and parsed your code. inplaceand inglobalsidentical. This is very intuitive: the compiler can store a constant string in a section .rodata.

, gcc infunc (. ), , , "" s . s static infunc , inplace inglobals.

0000000000000010 :
  10:   48 83 ec 18             sub    $0x18,%rsp
  14:   48 63 ff                movslq %edi,%rdi
  17:   64 48 8b 04 25 28 00    mov    %fs:0x28,%rax
  1e:   00 00 
  20:   48 89 44 24 08          mov    %rax,0x8(%rsp)
  25:   31 c0                   xor    %eax,%eax
  27:   c7 04 24 61 7a 53 00    movl   $0x537a61,(%rsp)
  2e:   0f b6 04 3c             movzbl (%rsp,%rdi,1),%eax
  32:   48 8b 54 24 08          mov    0x8(%rsp),%rdx
  37:   64 48 33 14 25 28 00    xor    %fs:0x28,%rdx
  3e:   00 00 
  40:   75 05                   jne    47 
  42:   48 83 c4 18             add    $0x18,%rsp
  46:   c3                      retq   
  47:   e8 00 00 00 00          callq  4c 

%fs:0x28 GCC. , :

0000000000000010 :
  10:   48 63 ff                movslq %edi,%rdi
  13:   c7 44 24 f0 61 7a 53    movl   $0x537a61,-0x10(%rsp)
  1a:   00 
  1b:   0f b6 44 3c f0          movzbl -0x10(%rsp,%rdi,1),%eax
  20:   c3                      retq   

, GCC . , , , .

, . , , , . GCC infunc , . inplace inglobals.

+2

, 1 3, 2 ( , , , ). , - , ( , , ).

, , ( 3). 1 2 , , 1.

, , , , 2 , 2.

+1

All Articles