我可以指望我的编译器优化 const char * 上的 strlen 吗?
在我的 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) 已被编译器优化是否安全?
(苹果示例代码 已经预先计算了 strlen(kFoo),但我认为这对于大量常量字符串来说很容易出错。)
编辑:优化动机:使用 NSXMLParser 在 iPod touch 2G 上解析我的 SVG 地图需要 5 秒(!)。所以,我想切换到lib2xml,并优化字符串比较。
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* sax_string,.....)
{
if ( strcmp(sax_string, kFoo, strlen(kFoo) ) == 0)
{
}
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果“LLVM”指的是 clang,那么是的,您可以依靠
clang -O
来优化strlen
。您的函数的代码如下:我将
strcmp
更改为strncmp
,但第三个参数确实已被立即的$3
替换>。请注意,gcc 4.2.1 -O3 不会优化此
strlen
调用,并且您只能期望它在您的问题的精确条件下工作(特别是字符串和对的调用) strlen
必须位于同一文件中)。If by "LLVM" you mean clang, then yes, you can count on
clang -O
to optimize thestrlen
away. Here is what the code for your function looks like:I changed the
strcmp
intostrncmp
, 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 tostrlen
must be in the same file).不要这样写:
您创建了一个名为
kFoo
的变量,它指向常量数据。编译器可能能够检测到该变量没有更改并对其进行优化,但如果没有,则程序的数据段已经膨胀。也不要写这样的东西:
现在你的变量
kFoo
是const限定的并且不可修改,但是如果它在位置无关的代码(共享库等)中使用,内容在运行时仍然会有所不同,因此它会增加程序的启动和内存成本。相反,使用:甚至:
Don't write things like:
You've created a variable named
kFoo
that points to constant data. The compiler might be able to detect that this variable does not change and optimize it out, but if not, you've bloated your program's data segment.Also don't write things like:
Now your variable
kFoo
isconst
-qualified and non-modifiable, but if it's used in position independent code (shared libraries etc.), the contents will still vary at runtime and thus it will add startup and memory cost to your program. Instead, use:or even:
一般来说,你不能指望它。但是,您可以使用“sizeof”并将其应用于字符串文字。当然,这意味着您不能按照最初定义“kFoo”的方式来定义它。
以下内容应该适用于所有编译器和所有优化级别。
In general you can't count on it. However, you could use 'sizeof' and apply it to a string literal. Of course, this mean that you can't define 'kFoo' the way it originally was defined.
The following should work on all compilers and on all optimization levels.