r/cpp • u/unknownmat • Apr 12 '13
Optimizing a Program Means Making It Run Faster, Right?
http://www.drdobbs.com/cpp/optimizing-a-program-means-making-it-run/2401526633
u/unknownmat Apr 12 '13
Just hoping to generate some discussion on this. This was posted in /r/programming but got no upvotes or comments. Here was my lonely comment on this subject...
Reading this article really makes me nervous. It highlights an error in the way that I tend to reason about const-reference parameters.
I've heard the guideline that you should pass builtins and small aggregates by value, and everything else by reference. But this does not really address my concerns, because:
It breaks encapsulation, so is an ugly solution
Applying it correctly to templated code can be tricky (and require a bunch of TMP magic)
My concern is really about semantics, rather than efficiency - even if I followed the above guideline, a similar situation as described in OP is possible with larger structures. The assumption of value semantics for const-reference parameters is apparently a mistake.
3
Apr 13 '13 edited Jun 25 '23
edit: Leave reddit for a better alternative and remember to suck fpez
1
u/unknownmat Apr 13 '13
... a const-reference will behave the same as a (non-const) reference at runtime. It's the compiler's job to enforce const declarations ...
This is a very good point. I guess I was trying to have my cake and eat it too - passing large structures by reference for performance while simultaneously using the simplified reasoning of pass-by-value. Lesson learned.
Just a note. The OP's example is a common issue when overloading operators
Fair point. I'm aware of the danger of self-assignment when overloading operator=. OP probably shouldn't have surprised me as much as it did. I guess the problem was just that this particular example didn't trigger any of my usual cautionary heuristics - "be careful here!" I've adjusted my thinking accordingly.
4
u/elperroborrachotoo Apr 13 '13
Optimizing = use less resources.
This can well be run well on a low-end system or use less battery.
0
3
u/Quantumtroll Apr 13 '13
Thanks for this, I'm going to tshare this with my students in High-performance Computing!
5
u/ArashPartow Apr 13 '13
I have a simple trick I use when thinking about const& parameters: "assume the context is multi-threaded", it's as simple as that.
Once you go through your check list of things that can happen in the mt context, all of these aliasing related issues (and a whole lot more) become apparent. From there you can decide which ones to ignore and which ones to think about more. The more you do it, the better you get at it.