Slice::concat performance

slice::concat seemingly returns a String, does it copy each slice into a new String? I think copying each slice is slow, can it be optimized to use pointers that point to different memory locations?

It copies the slices into one single String. It doesn't allocate a separate string for individual items.

No, a String always manages a single, contiguous buffer.

1 Like

You can look at the implementation here.

1 Like

Can we use unsafe to avoid copying? Maybe, raw pointers to different locations. But it may not implement Deref or DerefMut trait, dereferencing this unsafe type to &str may require those traits implemented by ourselves. However, does looking for different memory locations slow down the speed? If it also slows down the speed, which is faster compared to copying slices into one String?

I don't really understand what you are asking at this point. You can't force a String to form itself by chaining slices at different memory locations together, because a String is implemented as a flat buffer.

If you don't want a flat buffer, then just keep the slice of string slices around.

It's impossible to tell just like this. You'd have to benchmark it. But don't worry about it. Copying strings is usually not the bottleneck in most reasonable programs.

1 Like

I believe you're trying to implement a rope data structure.

There are Rust crates that implement this, such as ropey. If this is for a production app, it would probably be better to use an existing library that's been tried and tested than to write your own.

1 Like

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.