从 const char* + length 构造 const std::string 便宜吗?

Is it cheap to construct a const std::string from a const char* + length?

执行起来有多贵

const std::string s(my_const_char_ptr, my_length);

?是否涉及复制?如果不是,我可以从典型的标准库实现中获得多少指令?很少有人能在性能关键代码中使用它?

...或者我必须获得 GSL 实现并使用 string_view?

如果您想知道确切的答案,您需要在您的目标系统和编译设置上对其进行测量。但是对于引擎盖下发生的事情:

  • 如果my_length足够大(或者标准库的std::string实现没有使用小字符串优化——这种情况很少见),那么就会有一个动态内存分配.

  • 在任何情况下,从 *my_const_char_ptrstd::string 的缓冲区都会进行 O(n) 个字符的复制。

按照标准 table 66

basic_string(const charT*, size_type, const Allocator&) effects

data(): points at the first element of an allocated copy of the array whose first element is pointed at by s [...]

所以我们将有一个分配和一个 O(N) 副本,其中 N 是传递给函数的大小。

How expensive is it to execute...

如果你做一次就很便宜

? Is there copying involved?

是的,但这是您最不担心的事情。线性副本是您在现代建筑中可以做的最便宜的事情。 (由于流水线、预取等)

how many instructions can I expect from typical standard library implementations?

比您想象的要少 - 特别是在复制部分。该实现(使用 -O2 构建)将寻求在可能的情况下立即循环展开、矢量化和传输大字。内存对齐实际上将是性能的最大仲裁者。

Few enough to have this in performance-critical code?

如果它对性能至关重要,请预先分配字符串并重新使用它(参见 std::string::assign(first, last))。同样,复制位与芯片一样便宜。内存分配会杀死你,所以做一次。

... or must I get a GSL implementation and use string_view?

除非字符串绝对巨大。