Cost of cloning an &str

Hi there!

I've been looking for a little information I can't seem to find on the web, which is: is cloning an &str free? Or does it clone the entire data like a String::clone would?

For context, I need to clone the following structure:

pub struct Test<'a> {
    input: &'a str,
    // ...other fields
}

And wondered if it would be very cheap, even with very large inputs.

Thanks in advance for your help! :slightly_smiling_face:

&str is a Copy type (more generally, &T is Copy for all T), which means that clone is just memcopy. the std::mem::size_of::<&str>() is 16 on 64 bit System (two pointers wide), so it copies only a relatively small bit of data.

So yeah, napkin calculation suggests that it should be more or less free.

2 Likes

Thanks!

So that means that even cloning a 64 MB string won't be a problem, right?

right, even for 64mb string the std::mem::size_of::<&str>() would be 16 bytes, and, for Copy types, only those size_of bytes are cloned.

1 Like

Great! Thanks for your help :smiley:

Note that &str is not a string by itself; it's only a reference into already existing string. Cloning that string, of course, would be expensive (if this is real String and not something like Rc<str>, of course), but cloning a reference is cheap.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.