【发布时间】:2018-03-06 15:51:07
【问题描述】:
使用std::string_view,range::for_each 产生 exact 程序集,const char[N] 和 const char * 都传递给 std::string_view ctor
也就是说,这段代码
auto str = "the quick brown fox is jumping on a lazy dog\nthe quick brown fox is jumping on a lazy dog\n";
ranges::for_each(std::string_view{str}, std::putchar);
和
auto& str = "the quick brown fox is jumping on a lazy dog\nthe quick brown fox is jumping on a lazy dog\n";
ranges::for_each(std::string_view{str}, std::putchar);
两者都屈服于装配:
main: # @main
pushq %rbx
movq $-90, %rbx
.LBB0_1: # =>This Inner Loop Header: Depth=1
movsbl .L.str+90(%rbx), %edi
movq stdout(%rip), %rsi
callq _IO_putc
addq $1, %rbx
jne .LBB0_1
xorl %eax, %eax
popq %rbx
retq
.L.str:
.asciz "the quick brown fox is jumping on a lazy dog\nthe quick brown fox is jumping on a lazy dog\n"
此外,如果我们将 c 字符串作为const char[N] 传递给ranges::view::c_str(),
auto& str = "the quick brown fox is jumping on a lazy dog\nthe quick brown fox is jumping on a lazy dog\n";
ranges::for_each(ranges::view::c_str(str), std::putchar);
这会产生上面的精确装配,就像 std::string_view 产生的一样。
另一方面,如果我们将 c 字符串作为const char* 传递给ranges::view::c_str()
auto str = "the quick brown fox is jumping on a lazy dog\nthe quick brown fox is jumping on a lazy dog\n";
ranges::for_each(ranges::view::c_str(str), std::putchar);
这一次它产生了一个不同的程序集,如下所示:
main: # @main
pushq %rbx
movb $116, %al
movq $-90, %rbx
.LBB0_1: # =>This Inner Loop Header: Depth=1
movsbl %al, %edi
movq stdout(%rip), %rsi
callq _IO_putc
movzbl .L.str+91(%rbx), %eax
incq %rbx
jne .LBB0_1
xorl %eax, %eax
popq %rbx
retq
.L.str:
.asciz "the quick brown fox is jumping on a lazy dog\nthe quick brown fox is jumping on a lazy dog\n"
哪个大会获胜?
为什么std::string_view 决定生成相同的二进制文件?
view::c_str() 能否同时使用const char* 和const char [N] 产生一个更快的组装?
【问题讨论】:
-
我建议你挤进
c++标签。它比特定于版本的 c++ 标签更受欢迎。
标签: c++ optimization range-v3 string-view