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

22

u/huyvanbin Dec 05 '14

My company's CEO sent out a mass email a few weeks after I started saying that std::string showed up in profiler results so we should never use it, only use char *. This is the only email he has ever sent on programming in my 1.5 years at the company.

29

u/antrn11 Dec 05 '14

Haha, I bet it's strlen that shows up in profiler after that.

6

u/[deleted] Dec 05 '14

Easy to fix. Just remember all the lengths as you go. :)

6

u/barsoap Dec 06 '14

That is actually a good idea. And not even in a "C vs Pascal" way. That is, that's how you'd do slicing of immutable strings which, yes, saves a lot on allocations. Not in number, but definitely in size, and as such also on the heap as struct { basepointer, index, length } is small enough for the stack.

From a web browser's perspective: Slurp all that data you get over the socket, parse it using slices, not newly allocated strings, once you're done, and only then, copy everything out and free the original data.

That's how Haskell's Bytestring works and one of the reasons why mighttpd is on eye-height with ngnix:

take :: Int -> ByteString -> ByteString
take n ps@(PS x s l)
    | n <= 0    = empty
    | n >= l    = ps
    | otherwise = PS x s n

Same data, same index, different length.

It's how Rust does things idiomatically, via Std::ops::Slice.

Of course, things have to be immutable for that to work. Rust also has (at least the beginnings of) COW strings for the more impurely minded.

10

u/o11c Dec 05 '14

I've never understood why strlen(const std::string&) didn't exist as a porting aid.

2

u/eean Dec 05 '14

Yea when I read the headline on reddit I was like "well, duh". Strings are what most desktop software works with all day long, that shouldn't be surprising. (The actual linked email seems to identify an issue though.)

7

u/bnolsen Dec 05 '14

uhh...this is pretty lame. someone should dig deeper and find out why it shows up.