Libc++'s Implementation of std::string
joellaity.com
joellaity.com
IIRC, Facebook achieves this by using the last byte as the flag byte. To signify short string mode, this flag is set 0. This allows it to also serve as the null terminator. Tricky!
The history of those demonstrate some of the bat-shit insanity of the evolution of C++. Originally data didn't have to null-terminated, but then they finally realized that making c_str actually work without this invariant in general was nearly impossible. So since C++11 data and c_str are equivalent.
Edit: by impossible I really mean something usable with sane complexity requirements -- that wouldn't make people just immediately discard std::string for something better. This is the same C++ that brought you auto_ptr, and other garbage. C++11 corrected many things, this included.
NUL-terminated strings were one of the dumber things C++ inherited from C, and code that depends on NUL termination is not a thing to be proud of.
Basically the NUL-terminator amounts to a 1-byte of wasted space -- which is almost always completely in the noise -- if you're using std::string for tiny strings you're paying at least 24 bytes anyway. There are just very few cases where that one extra byte matters.
I think the overwhelming opinion is that this 1-byte trade-off is better than the overhead of allocation and copying when you want to pass that string around. NUL-terminated strings aren't important in C++ because of C (well, not directly), but because they are essentially the ABI of countless existing libraries and the major operating systems.
> code that depends on NUL termination is not a thing to be proud of.
Whatever. Code that depends on NUL termination is ubiquitous.
You have not thought it through. There was always space for a NUL, but nobody needs it to have a NUL in it until somebody calls c_str(). Anyway, that was true until somebody jiggered the Standard, just before 1998, to require a NUL visible to s[s.size()].
>C Code that depends on NUL termination is ubiquitous.
Fixed that for you.
No.
This is not technically true. You could plugin your hated NUL byte in the implementation of operator [].
> C Code that depends on NUL termination is ubiquitous.
No, that's not what I said. It really doesn't matter what language underlying the API of all the code that expects NUL terminated strings is written in (a lot of it is C++ of course too). Windows, MacOS, and all POSIX-ish systems have a large API that consumes NUL terminated strings. NUL terminated strings are ubiquitous in computing at this point. Sure blame C from 40 years ago and burn a dmr effigy, I don't care, but that battle was long lost.
NUL terminated strings may be terrible, but the C++ accomodation for them is not -- its a well-thought out trade-off. My understanding is that neither go nor Rust make this trade-off. golangs FFI and syscall overhead has always been something of a performance disaster anyway. C++ has always had a greater demand to "play nice" with legacy code and systems then either of those.
The overhead of just having the NUL-byte is almost always a non-factor. If it really is, then use a byte vector.
If you think anybody is complaining about the extra space for the NUL, what you are barking up is not even a tree.
> Evidently that is a minority preference.
What evidence? Pointing out a fact isn't an endorsement.
> If you think anybody is complaining about the extra space for the NUL
Then what exactly are you complaining about? Setting the byte to 0? If not, why are you being so obtuse?
> what you are barking up is not even a tree.
In this thread your tone is repeatedly that of a condescending jerk.
[1] with a compiler flag use_cxx11_abi=0 or something
Though I hear that the definition of big-O notation has shifted a bit in Silicon Valley these days so maybe that answer would get me in trouble in an interview.
So I can see why someone would claim that implementing size() via strlen() "only" for small strings shouldn't be considered O(1), because strlen() is O(n) and within that class of strings the runtime is increasing as the length increases.
Suppose I have a string and I take a reference to a character:
std::string a = f(); // shared
char& c = a.front();
Should the string be copied or not? One might argue, no taking a reference is different from "writing" so no copying, but one might also argue that reference can be used to change the string later, and the string doesn't know when this would happen so it has to pessimistically make a copy.You get bugs if you go with the former, and bad performance if you go with the latter.
const char& c = a.front();
Unfortunately the STL has an overload for the non-const version, which would cause this problem. It's hard to imagine the cases where you'd need a mutable reference to a single character. It can fit into the same register that the reference would live, so even as an immutable reference it doesn't make much sense. s[3] = 'h';
involves forming a mutable reference and then assigning its pointee.The way I think about it, to make CoW strings really usable in C++, you basically have to make strings immutable, like many newer languages like Python. That ship has sailed by the time standardization for C++ happened.
Result: many programs forgot
Convention: every non-NULL pointer returned by malloc() should be passed to free() at most once
Result: programs free()'d these pointers twice
Convention: programs should only write to memory addresses [p, p+s) if p is a non-NULL pointer returned by malloc(s), and before calling free(p)
Result: many programs wrote beyond p+s, or wrote to the memory after calling free()
Remind me again, what's a convention?
The benefit of a shared string is you might save some space. That’s fine but I think most programmers today will choose am explicitly shared type when they need it, and a fast string for most cases.
One important update is that the primary rationale for us, at the time, to change std::string's implementation to `fbstring` was to get SSO. We got huge perf wins for having SSO on std::string. (small string optimization for those unfamiliar with the initialism).
This, at the time, was a violation of the standard. By wording, SSO was not standard compliant.
Once the standard was changed (as of C++11) so that std::strings could have SSO, we removed our patches on the standard library and now use "vanilla" std::string (from libstdc++). We still have `folly::fbstring` for people who want that implementation (which is smaller, and has more in-situ capacity, because of various cleverness detailed in that talk), but it's no longer our `std::string`.
For reference: https://github.com/facebook/folly/blob/master/folly/FBString...
It always impressed me how clever it was, but once you know it it seems fairly clean and maintainable with no obvious downsides.
Branches on their own aren't particularly expensive (especially not an easily predictable one like this), but they do screw with several compiler optimizations (auto-vectorization, for one). Given that, it seems like a reasonable decision, and the only way you'd know which one is faster is just testing it.
I'd personally think it would be interesting to test artificially increasing the sizeof() of strings from 24 bytes (the minimum needed to store a pointer, size and capacity) to something like 64 bytes, just to get longer strings using the SSO. The trade-off in the stack-space of the string seems like it would totally be worth it, and with 56 character long "small strings", a huge number of strings could fit in there (virtually all names, for instance). You probably couldn't do it for std::string (would wreck havoc with ABIs), but my hunch is that performance and memory usage might both benefit from the reduced memory allocations.
The "optimal" implementation would actually have different allocation sizes when used mostly for processing and when used mostly for storage: for processing one would prefer bigger defaults, for storage, one needs as little as possible initial overhead.
That could be achieved by raising the knowledge of that distinction and introducing actually (at least) two kind of strings. And even more than that can be gained by recognizing that whenever the strings are involved in some more complex structures, some additional restrictions for totality of all associated strings could also be exploited: allocating the strings separately is an overhead by itself.
If I remember correctly, Turbo Pascal strings had the default size of 256 bytes and that's how much was on the stack for each, and that was fast even decades ago. That was not efficient for having a lot of them in the structures, if a lot of them could be smaller, but that was what a programmer had to care separately - still the typical processing of strings and working with the limited number of them was nicely covered by that default.
typedef unsigned char Str255[256];
typedef unsigned char Str63[64];
typedef unsigned char Str32[33];
typedef unsigned char Str31[32];
typedef unsigned char Str27[28];
typedef unsigned char Str15[16];
The 2^n-1 sizes are cache-line don’t need explanation, I think. 27 was the maximum length of a volume name in MFS, the original Macintosh file system (which was a strange mix of backwards (no directories) and forwards (255 character file names) thinking).Str32 was used in AppleTalk (and probably a design error or bug; Str31 is a more ‘natural’ type)
It is probably just a small win and not everybody wanted to pay for the extra complexity (SSO is already fairly complex).
Re your suggestion on large SSO, years ago, when doing document clustering, using large fixed size strings (64 chars if I remember correctly, longer strings were just truncated) was a huge win for me (even coping them around wasn't an issue). Not sure if it is appropriate for a general purpose string though.
edit: never mind, I see what you mean about having to check the size.
[0]: https://github.com/facebook/folly/blob/master/folly/FBString...
Note that the branch can be implemented in a way that compilers will lower into a CMOV, making the code size issue almost moot. I implemented that in fbstring back in the day:
https://github.com/facebook/folly/commit/be4c6d6b3e21914df8a...
This is the entirety of size():
0f b6 57 17 movzbl 0x17(%rdi),%edx
b8 17 00 00 00 mov $0x17,%eax
48 29 d0 sub %rdx,%rax
48 0f 48 47 08 cmovs 0x8(%rdi),%rax
A bit more than a MOV, but not that much.> I'd personally think it would be interesting to test artificially increasing the sizeof() of strings from 24 bytes (the minimum needed to store a pointer, size and capacity) to something like 64 bytes, just to get longer strings using the SSO
And libstdc++ is actually 32 bytes :( It's easy to template on the inline capacity, you can look at llvm::SmallVector or folly::small_vector, but vocabulary types should have the smallest possible footprint. Vast majority of instances are either empty, or very small (think keys in a map).
Many of the early implementations of `std::string` were COW (copy-on-write), which is not entirely compatible with SSO strings. In practice, COW strings proved to be troublesome and slow, and the SSO strings won out. The standard was changed to effectively mandate SSO strings and forbid COW strings.
The COW strings also were a constant source of surprising behavior. As with any COW object you have to make sure that the copy happens before and write. Simple enough, but the STL-style interface does not support this well. All you had to do is call operator[] or begin() on a non-const std::string and it would force a copy.
This meant that something that to the programmer clearly looked like a read-only operation like:
if (str[2] == 'x') { ...}
...could end up copying the string. Worse, it also meant that any previously taken references are now invalidated. This lead to horrible bugs where you would hold a pointer at the previous copy of the string (which you no longer own a refcount on) and it would almost always work... but every so often another thread would come by and reuse the memory behind your back.So COW std::string was a long festering mess in C++. Their removal in C++11 was completely warranted.
https://github.com/bloomberg/bde/blob/master/groups/bsl/bsls...
This is fine because std::string is provided by the standard library and the standard library is allowed to do stuff normal libraries are not allowed to do. This technique does work in practice, but it is technically undefined behavior.
How does this work, given that it's still written in C++? Is there special casing in the compiler to define the behavior?
If it were to be special-cased, it would probably require an attribute or a pragma or something. While it's not unheard of for compilers to automatically detect they are compiling the standard library, it's fairly rare.
I say this as someone with a full time paid job supporting libc++ compiled by another compiler for a commercial organization in a safety context.
One consequence is that portable code can't depend on any particular behavior because it can be different between implementations. Every implementation will do something, but each one may do something completely different.
Another consequence is that "undefined behavior" isn't undefined in the context of a specific implementation because you can look at what it does and see how it's defined in that implementation. In this case, libc++ is essentially part of the implementation, so it's fair game for it to depend on implementation details of clang.
> Every implementation will do something, but each one may do something completely different.
If I'm reading this correctly, you're saying that we can depend on each compiler providing a consistent way of handling each kind of undefined behaviour.
That's not correct. That describes implementation-defined behaviour, which is different. [0]
Compilers do not have to decide what behaviour should result from a particular kind of undefined behaviour, and then commit to ensuring that behaviour occurs consistently. That's the point of undefined behaviour: the compiler is permitted to assume the absence of undefined behaviour, and to optimise accordingly.
If you have undefined behaviour in your C++ code, you are not guaranteed to see consistent program behaviour. Your program is ill-formed. All bets are off, throughout the entire lifetime of your program. [1] (In C++, undefined behaviour can 'travel back in time', meaning that if your program invokes undefined behaviour, the behaviour across the entire lifetime of your program is made undefined.)
A compiler may choose to commit to a certain behaviour for a certain type of undefined behaviour (such as guaranteeing wrap-around behaviour for signed overflow), but it is not required to.
A compiler is required to define a consistent value for sizeof(int), because that's implementation-defined. [0]
> Another consequence is that "undefined behavior" isn't undefined in the context of a specific implementation because you can look at what it does and see how it's defined in that implementation.
This isn't right.
Unless the compiler's documentation tells you that you can rely upon its handling of the relevant undefined behaviour, then then compiler is not required to provide consistent behaviour for any particular kind of undefined behaviour.
> In this case, libc++ is essentially part of the implementation
It's not, as it's not tied to one compiler. [2]
[0] https://stackoverflow.com/a/4105123/
Moreover, there are additional guarantees when reading through char types, as well as unsigned types, so depending on the precise code things may very well be totally well defined.
C doesn't disallow type punning. The gotchas mostly have to do with visibility to the compiler, otherwise the compiler may reorder loads and stores. The safest way to do type punning is through union members as the standard makes additional guarantees that restrict the types of optimizations a compiler can make.
/*
* structure to access an integer
*/
struct
{
int integ;
};Except when the union member you are reading is a 'common initial sequence' [1] of the union member that was written, to be precise ;-). But that's not the case here.
...and the reason short strings are that length is precisely because a long string needs that amount of space to store the pointer, capacity, and used variables anyway. On a 32-bit system, the short string limit is lower by half.
Also, as optimised as this implementation is, I have yet to see a compiler that's smart enough to do things like replace "dumb" uses of std::string with essentially the equivalent of what a smart C programmer using pointers would write (as the saying goes, "the fastest way to do something is to not do it at all.") Ditto for the other data structures in the library. In other words, optimising individual classes approaches a local minima.
I agree with your observations, but I don't know if I agree with this part. For example, if you've already chosen to make a dynamic-resizing heap buffer, you're probably going to write something no better than std::vector. I know this because I've written the same thing many times working in .c files. It's handy to have that one standardized.
Of course, the lack of a good one of those will make the dynamic-resizing heap buffer a less common choice in C, so in that sense maybe you're right.
What is the complaint though? Bad realloc strategy?
Come to think of it, the worst part of how vectors historically have been was not vector itself, but the requirement to use the copy constructor at reallocation time. C++11 and move semantics fixed that.
In particular vectors with class type iterators (as opposed to using raw pointers) paid an heavy penality. Is it possible that your vector used raw pointers as iterators?
Of course, the lack of a good one of those will make the dynamic-resizing heap buffer a less common choice in C, so in that sense maybe you're right.
Precisely. If you need a dynamically resizeable buffer then using std::vector will be a very good idea, but perhaps you don't really need it; the lack of such "ready-to-use" data structures in C encourages more thought on whether it's necessary to do so, and as a result you might end up with a more efficient solution which doesn't.
Another example is using a std::map<char, something> - no compiler I know of will replace that with a 256-element array, despite the latter being much more efficient than the former when you use most of the values.
Can you give an example?
For example, removing a prefix the C way would be to add the size of the prefix to the pointer.
I guess c++ has string_views for that sort of case as of c++17.
Surely to do this you'd still have to keep either a reference to the original pointer around or remember the offset so you could `free(str)` with the correct pointer?
Firstly not all strings are on the heap, but ignoring that... If somebody passes you a pointer to a string and you aren't going to hold onto it for a while, you can just add to the pointer and it's no big deal. But yes, if you own the allocation, you need to keep the old pointer too.
But I guess these people have run the benchmarks. ...Or maybe not. I have to wonder.
Modern CPUs have branch prediction.
The predictors work by caching which branches were taken, and assuming the same outcome is likely to happen next time the branch at that address is checked. That particular branch is checked all the time, and unless you actually have >2GB strings the result is always the same.
Only branches which dynamic runtime behavior are bad for performance, like binary search when the same branch is taken/not taken randomly, depending on the data and the key being searched. Branches with stable runtime behavior are OK thanks to branch prediction. Examples of good branches: `while( i < 10000 )`, `if( string_length < INT_MAX )`
Consider the implications to inlining: the size getter is a prime candidate, but suddenly it gets less predictor-friendly.
Edit: this is naturally a good case for manual hinting.
struct not_too_long_string {
char* data;
uint32_t size;
uint32_t capacity;
};
Of course, if you do it that way then the longest string you can store with the small string optimization is probably ~15 bytes instead of ~23. So although you do save 1/3 on the size of each string, on average you're probably still going to end up doing a greater number of dynamic allocations because of the reduced small string capacity. Unless of course you know a priori that a sufficiently large portion of your strings will be > 15 bytes anyway, which of course the implementors of std::string almost certainly don't know.Edit: I failed to notice the part about the length being in the data block (doh). I guess the disadvantage to putting the length there would be that an extra indirection is required to get the length, a rather common operation. And as others have pointed out, that only saves 4 bytes, which will be used anyway for alignment..
It would require an additional branch to test for huge strings, but it will be almost never executed, and I think modern CPUs are pretty good at optimizing out such branches...
You cannot assume anything about the state of a moved-from object. AFAIK, the only valid operations are destruction and assigning something else to it.
This is the right default assuption, but classes are allowed to have (and document) more specific behaviour. For example, it is guaranteed that std::unique_ptr and std::shared_ptr are empty (nullptr) after they have been moved from, and std::vector is guaranteed to be empty after it is moved from so long as the destination allocator is the same.
> AFAIK, the only valid operations are destruction and assigning something else to it.
Even for classes whose move constructors have no guarantees, there are often other methods that don't have any preconditions, such as calling clear() or resize(0). In fact is it allowed to call other operations and they should behave consistently, it's just not guaranteed what exact value the object should have (e.g. if size() > 0 then .at(0) should not throw and a second call to it should return the same value as the first call to it).
Even if I did know every single edge case in the language and library, the developers next to me might not. Then they decide to emulate me (many learn by example) and catastrophe ensues.
You don't really need to make an assumption about being 1 byte wide. That's guaranteed by the standard.
>Depending on the computer architecture, a byte may consist of 8 or more bits, the exact number being recorded in CHAR_BIT.
I'll add that as an assumption.
This will bring sizeof(string) to a size of a single pointer and will still allow for short strings of 7 chars (in 64-bit builds).
Memory allocations are usually aligned by default, so the pointers will have at least one lower bit cleared and available to be used as a mode flag.
If in doubt, allocating through aligned_alloc(2,...) will guarantee an unused bit in a pointer.
I'll mention though that std::string (well, basic_string) takes an allocator parameter, so it could only enable this optimization for 'well known' allocators that provide aligned buffers.
But it is mostly for historical reasons. I believe the original STL used the SSO optimiziation [1], so there was never any assumption about the stability of references to string elements, while there is a lot of code that assumes that references to vector elements do not change.
[1] The SGI STL, direclty derived from the original HP STL had extensive rationale on why it didn't implement COW; libstdc++, which I believe also traces its roots from it, decided to instead do COW. The rest is history.
Does the edit button disappear after a certain amount of time?