什么是强力清除? [英] What is strlen elision?
问题描述
我可以看到它列出的内容作为现代C ++习惯用法之一,但是究竟是什么呢?
这只是复制省略?
您可能知道 std :: strlen
遍历整个字符串。在某些情况下,这可能效率不高,因为这意味着CPU必须开始对字符进行计数,从而减少了其他内容的缓存位置。
但是在大多数情况下,编译器能够优化 std :: strlen
并计算字符数字符串本身而不是使结果程序执行该操作。
A std :: strlen
的简单示例完全可以完全优化。
#include< cstring>
int main(){
return std :: strlen( hi);
}
-O3以下
得到的程序集是
main:#@main
mov eax,2
ret
即使 -O0
不生成循环!
现在这是一个非常简单的示例,但是它可以工作甚至对于 std :: strlen
的用法也更复杂。
#include< cstring>
int main(int argc,char **){
const char * string;
if(argc == 1)
string = hello;
else if(argc == 2)
string = world;
else if(argc == 3)
string =!;
return std :: strlen(string);
}
这里的字符串完全是已优化,以及 std :: strlen
调用。
I can see it listed as one of the modern C++ idioms, but what it is exactly?
Is it just a type of copy elision?
You might know that std::strlen
loops over the whole string. This can be inefficient in some cases, as it means that the CPU has to start counting characters, which reduces cache locality for other stuff.
But in most cases, the compiler is able to optimize std::strlen
and count the number of characters of the string itself instead of making the resulting program do it. This is sometimes called strlen elision (because it elides the call to strlen).
A simple example of std::strlen
would simply get optimized completely.
#include <cstring>
int main() {
return std::strlen("hi");
}
Under -O3
the resulting assembly is
main: # @main
mov eax, 2
ret
Even under -O0
no loop is generated!
Now this is a rather simple example, but it works even for a bit more complicated usages of std::strlen
.
#include <cstring>
int main(int argc, char**) {
const char *string;
if (argc == 1)
string = "hello";
else if (argc == 2)
string = "world";
else if (argc == 3)
string = "!";
return std::strlen(string);
}
Here the strings are completely optimized away, as well as the std::strlen
call.
这篇关于什么是强力清除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!