空字符串转换为 Box 时会分配吗<str>?

问题描述 投票:0回答:2

我正在为我的应用程序使用消息传递架构。一种常见的类型是

io::Result<Box<str>>
。有时,我想传递一个空字符串。这样做时会发生任何分配吗?

fn pass_empty_string(tx: mpsc::Sender<io::Result<Box<str>>>) {
   tx.send(Ok("".into())) 
}
string rust memory-management
2个回答
1
投票

不。控制流经过几个函数,但最终到达

RawVec::allocate_in()
,其中有以下检查:

        // Don't allocate here because `Drop` will not deallocate when `capacity` is 0.
        if T::IS_ZST || capacity == 0 {
            Self::new_in(alloc)
        }

如果字符串是常量,LLVM 也会优化代码

但是,请注意,这不是 保证


0
投票

基准测试库

divan
有一个分配跟踪器可以帮助我们回答这个问题。在
benches/alloc_test.rs

fn main() {
    divan::main();
}

#[global_allocator]
static ALLOC: divan::AllocProfiler = divan::AllocProfiler::system();

#[divan::bench]
fn allocates() -> String {
    String::from("hello")
}

#[divan::bench]
fn maybe_allocates() -> Box<str> {
    "".into()
}

然后,当我们运行基准测试时...

$ cargo bench

     Running benches/alloc_test.rs
Timer precision: 12 ns
parser              fastest       │ slowest       │ median        │ mean          │ samples │ iters
├─ allocates        4.918 ns      │ 25.84 ns      │ 5.168 ns      │ 7.119 ns      │ 100     │ 6400
│                   alloc:        │               │               │               │         │
│                     1           │ 1             │ 1             │ 1             │         │
│                     5 B         │ 5 B           │ 5 B           │ 5 B           │         │
╰─ maybe_allocates  0.233 ns      │ 3.125 ns      │ 0.239 ns      │ 0.277 ns      │ 100     │ 102400

...我们发现事实并非如此!

© www.soinside.com 2019 - 2024. All rights reserved.