4 ms·
At the very least, retrieving data from a &String will involve two pointer lookups (one for the &, one for the internal pointer in the String) whereas plain Str
by dbaupp 6y ago
At the very least, retrieving data from a &String will involve two pointer lookups (one for the &, one for the internal pointer in the String) whereas plain String and &str involve just one.
In addition, since the String object itself cannot be mutated, a slice like s[10:20] as a &String requires storing the 10 and 20 outside the String and then doing pointer offsets when reading the data. A &str does not need to do this, because the pointer offset happens on creation. Because of this, the &str is also smaller (and this is more efficient because of caches), because it only needs to store a pointer and length (16 bytes, on typical machines), while a &String needs to store at least a pointer to the String and the start/end indices (24 bytes).
One could have various special cases to make &String “work” but it likely ends up being equivalent to &str. The key piece in mind: if one retains the &String name, it makes the language less orthogonal, with more special cases, because taking a reference to a string variable like &s to get a value of type &String behaves very differently to taking a reference to any others like &some_int (of type &i32), which will cause problems in generic code.
- Misdicorl 6y agoWhat issues arise by aliasing &str and &String to the same (&str) implementation? Does any code actually rely on &String pointing at the String itself rather than the bytes of the string? Perhaps its more strange/broken to special case &String that it is to have the (imo) warty &str.
- dbaupp 6y agoUnsafe generic code likely cares, where it is coercing a &T to a *const T and then relying on pointer stability/consistency. It will also cause difficulties with methods like ‘.capacity()’, because that info is lost with &str.