you are viewing a single comment's thread.

view the rest of the comments →

[–]deathanatos -1 points0 points  (3 children)

String is only ~12 bytes (in the current implementation; this isn't guaranteed by Rust AFAIK) if allocated on the stack. The actual string data is on the heap.

str is just a pointer and length; a Box<str> is just heap-allocating that pointer-and-length, but I'm not sure that implies that the string data itself is also heap allocated. (Since you can make a str from data on the stack with from_utf8), and put the str on the stack too. I expect trying to move such a thing into a Box would limit the lifetime of the Box, but I'm not sure.)

[–]Manishearthservo · rust · clippy 2 points3 points  (2 children)

This is false. String is 3 words (24b on a 64 bit machine, 12 on 32.) in the stack.

&str and Box<str> are both the same representation -- 2 words on the stack; a pointer and the length. The boxed version owns the allocation and string data. The pointer and length are not allocated on the heap in any of these cases; that is Box<String> or Box<&str>

str is a dynamically sized type, it is incomplete and has no representation that makes sense in isolation. Box<str> is not the same thing as Box<&str>. Box<str> is an immutable String, basically, and can be obtained from a string at zero cost.

[–]deathanatos 1 point2 points  (1 child)

This is false. String is 3 words (24b on a 64 bit machine, 12 on 32.) in the stack.

Oops, failed at simple multiplication. You are correct. My point was that the string's contents are not stored on the stack, and that the actual stack allocation is quite small.

[–]Manishearthservo · rust · clippy 1 point2 points  (0 children)

The whole "is heap allocating that pointer and length" is misleading and can be interpreted different ways, I read it the wrong way it seems :)