can I count on my compiler to optimize strlen on const char *?

前端 未结 4 757
后悔当初
后悔当初 2021-01-04 03:34

In my SAX xml parsing callback (XCode 4, LLVM), I am doing a lot of calls to this type of code:

static const char* kFoo = \"Bar\";

void SaxCallBack(char* sa         


        
4条回答
  •  悲哀的现实
    2021-01-04 03:51

    If by "LLVM" you mean clang, then yes, you can count on clang -O to optimize the strlen away. Here is what the code for your function looks like:

    _SaxCallBack:
    Leh_func_begin1:
        pushq   %rbp
    Ltmp0:
        movq    %rsp, %rbp
    Ltmp1:
        leaq    L_.str1(%rip), %rsi
        movl    $3, %edx
        callq   _strncmp
        ...
    

    I changed the strcmp into strncmp, but the third argument has indeed been replaced by the immediate $3.

    Note that gcc 4.2.1 -O3 does not optimize this strlen call, and that you can only expect it to work in the precise conditions of your question (especially, the string and the call to strlen must be in the same file).

提交回复
热议问题