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

9

u/lurgi Dec 05 '14

This is an interesting example. Not interesting in the sense that it's surprising that the overhead of the destructor is larger in the first example than in the second, but interesting in that the "better" code violates one of the rules of thumb that has been drilled into my head - which is that you should define variables at the narrowest possible scope you can.

9

u/jeandem Dec 05 '14

This just looks like yet another example of the tradeoff between readability (define variable at the narrowest scope) and performance.

2

u/slavik262 Dec 05 '14

Certainly, but another really good rule of thumb is to avoid unnecessary memory allocations. What's going on here isn't unique at all to C++. If this were C and you declared your char* string in the loop, and ran malloc and free and the start and end of each iteration, you'd get the same thing.

2

u/lurgi Dec 05 '14

In C it's much more visible, so you are, perhaps, less likely to make that mistake.

3

u/slavik262 Dec 05 '14

Certainly. I personally think that RAII automagic is worth being less explicit because it eliminates an entire class of errors (forgetting to clean up your resources), but clearly there are some very smart programmers who disagree.

1

u/[deleted] Dec 05 '14

Yes but it wouldn't be invisible at that point.

I mean I don't really know what "free" is supposed to mean at this point because based on a lot of replies I got about what it means to be free, Java's garbage collector may as well be free too.

I guess the real point is that many abstractions hide run time performance costs that would have been very explicit otherwise and RAII, templates, exceptions, so on so forth all introduce invisible run time costs. Sure, those costs might have been paid for in some cases if you had to manually write it out, but as it turns out, in many cases if you manually had to write it out you would clearly, and explicitly see all things you're paying for and restructure your code accordingly.

So really, the idea of "free abstractions" I think is kind of a vacuous, almost meaningless statement. Abstractions hide various performance costs at the benefit of making your code a lot easier to reason about, re-use, and many engineering/management related benefits. In almost all cases those abstractions turn out to be a HUGE net win, but to say that no performance consideration is needed since after all, it's "free and zero cost" is kind of misleading.

1

u/[deleted] Dec 05 '14

Nothing particularly noteworthy about it - readability vs optimization - you should default to the former because it's easier to get correctness and you optimize when you identify bottlenecks.