在C ++中,当连接一串字符串(其中每个元素的大小大致已知)时,通常会预先分配内存以避免多次重新分配和移动:
std::vector<std::string> words;
constexpr size_t APPROX_SIZE = 20;
std::string phrase;
phrase.reserve((words.size() + 5) * APPROX_SIZE); // <-- avoid multiple allocations
for (const auto &w : words)
phrase.append(w);
类似地,我是在Rust中完成的(此块需要unicode-segmentation板条箱]
fn reverse(input: &str) -> String {
let mut result = String::with_capacity(input.len());
for gc in input.graphemes(true /*extended*/).rev() {
result.push_str(gc)
}
result
}
有人告诉我,惯用的方法是单个表达式
fn reverse(input: &str) -> String {
input
.graphemes(true /*extended*/)
.rev()
.collect::<Vec<&str>>()
.concat()
}
虽然我真的很喜欢它,并且要使用它,但从内存分配的角度来看,前者分配的块数会少于后者?
我用cargo rustc --release -- --emit asm -C "llvm-args=-x86-asm-syntax=intel"
对此进行了反汇编,但其中没有散布的源代码,所以我很茫然。
您的原始代码很好,我不建议更改它。