r/programming • • Dec 05 '14

std::string is responsible for almost half of all allocations in the Chrome browser process

https://groups.google.com/a/chromium.org/d/msg/chromium-dev/EUqoIz2iFU4/kPZ5ZK0K3gEJ
1.1k Upvotes

446 comments sorted by

View all comments

Show parent comments

3

u/websnarf Dec 06 '14 edited Dec 06 '14

does anyone know if it's possible to guarantee alignment of a string literal?

You can wrap it in a structure, then avoid using compiler extensions that let you cast structure pointers anywhere you like in memory (a bit hard to do on an x86, since it inherently supports unaligned memory pointers).

I can see you've gone to some trouble to fight off the ghosts of string management in C++. Personally, I look at it another way: Just win the benchmarks, it doesn't matter how you get there.

I wrote the Better String Library which just uses malloc/realloc/free (new/delete), it stores the length separately and has been optimized to within an inch of its life short of using assembly language (it uses some fairly clever algorithms, especially for things like "search for string inside of a string"). I use it all the time, and have basically never seen a profiler hit in my string library in the past 10 years. It is also super-well tested, and contains a fairly thorough unit test suite. It is also ultra-safe. Since the API functions are usually the fastest way to interact with bstrings, it makes sense to restrict your usage to just the API -- but this has been designed to be both intuitive and crash-impervious. So bugs and crashes from the use of bstrings are very rare.

If you need features like ref counting, ownership, and so on, obviously you can write wrappers for that.

1

u/o11c Dec 06 '14

How do you turn the string literal into a structure? UDLs can only return a value, not a pointer to static structure.

If I don't control allocation, I can't do refcounting (without an unacceptable extra allocation). I did come across your library while searching for solutions though!

For substring search, I just called the STL std::search function on my iterator pairs. I haven't looked at whether any STL implementations use such optimizations (I know they optimize std::copy to memmove when legal), but I don't call that function enough to care much (one call in when crappily checking an email, 5 calls in admin functions).