我可以指望我的编译器优化strlen上的const char *? [英] can I count on my compiler to optimize strlen on const char *?
问题描述
在我的SAX xml解析回调(XCode 4,LLVM),我正在做很多调用
这种类型的代码:
static const char * kFoo =Bar;
void SaxCallBack(char * sax_string,.....)
{
if(strcmp(sax_string,kFoo,strlen(kFoo))== 0)
{
}
}
是否可以假设strlen(kFoo)是由编译器优化的?
(Apple示例代码
预先计算了strlen(kFoo),但我认为这对于大量的常量字符串来说是容易出错的) p>
编辑:优化的动机:在iPod touch 2G上解析我的SVG地图需要5秒(!)使用NSXMLParser。因此,我想切换到lib2xml,并优化字符串比较。
如果LLVM是的,你可以依靠 clang -O
来优化 strlen
。以下是您的函数的代码如下:
_SaxCallBack:
Leh_func_begin1:
pushq%rbp
Ltmp0:
movq%rsp,%rbp
Ltmp1:
leaq L_.str1(%rip),%rsi
movl $ 3,%edx
callc _strncmp
...
我改变了 注意,gcc 4.2.1 -O3不会优化这个 In my SAX xml parsing callback (XCode 4, LLVM), I am doing a lot of calls to
this type of code: Is it safe to assume that strlen(kFoo) is optimized by the compiler? (The Apple sample code
had pre-calculated strlen(kFoo), but I think this is error prone for large numbers of constant strings.) Edit: Motivation for optimizing: parsing my SVG map on iPod touch 2G takes 5 seconds (!) using NSXMLParser. So, I want to switch to lib2xml, and optimize the string comparisons. If by "LLVM" you mean clang, then yes, you can count on I changed the Note that gcc 4.2.1 -O3 does not optimize this 这篇关于我可以指望我的编译器优化strlen上的const char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! strcmp
into
strncmp
,但第三个参数确实已被立即 $ 3
>
strlen
调用,并且你只能期望它工作你的问题的确切条件(特别是字符串和 strlen
的调用必须在同一个文件中)。static const char* kFoo = "Bar";
void SaxCallBack(char* sax_string,.....)
{
if ( strcmp(sax_string, kFoo, strlen(kFoo) ) == 0)
{
}
}
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
...
strcmp
into strncmp
, but the third argument has indeed been replaced by the immediate $3
.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).