views:

153

answers:

2

E.g.

vector<string> a;

vector<string> b;

a.push_back("first");

b=a;

Would it be optimised somehow as

vector<string> b;

b.push_back("first");
+6  A: 

Short answer: Yes.

Long answer: Not really an "optimization", as most modern compilers (read as: non-MSVC) will do that. It's called static single assignment (SSA) and GCC supports it since version 4.0 - and it kicks ass, too!

LiraNuna
That is cool. Thanx for the info!
AlexKR
I am surprised that you do not call it an optimisation.
Aftershock
I believe the term "optimization" has many, many vague definitions. I believe this type of "optimization" is better to be called "correction".
LiraNuna
SSA doesn't automatically apply here. It is typically applied to primitive datatypes (or just on registers), but in high-level C++ code, assignments and constructors might have side effects, so the compiler has to check that it is safe to optimize away. And yes, then it is definitely an optimization.
jalf
+1  A: 

Well, you're saving yourself a call to operator=...

You should always remember the 2 rules of optimization though.

“The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.” - Michael A. Jackson

Gab Royer
I hate that catchphrase, people who never worked with embedded systems have the luxury of working on fast machines that become sloppy and believe the compiler will do their job for them. Please read http://www.liranuna.com/sse-intrinsics-optimizations-in-popular-compilers/ so you can see how bad compilers can be sometimes.
LiraNuna
Optimization is GOOD - just not in large quantities. Don't spend too much time on optimization but don't leave a program unoptimized. Just like a healthy diet, people NEED sweets in their life, even though it's considered "BAD" to consume.
LiraNuna
+1 to LiraNuna. These rules of software optimization are nonsense (I wonder how many adepts they have...)! It should be "Learn to optimize", but not "Don't optimize".
SadSido
I'd go with "Measure before you optimize: the bottleneck won't always be where you expect it."
Jurily
I've spent a lot of time writing embedded code. It's true: Don't optimize!
ziggystar
This should concern micro-optimizations. It does not mean: Do not consider performance at all when choosing data structures, algorithms, ... In particular, OP is asking if he can rely on this rule when making larger-scale decisions, because if it turns out that the compiler is not smart enough, he might end up with lots of needless copying which could have been avoided by thinking a bit more about the program design. (IMO, you can get the design so wrong, that you just can't optimize the bottlenecks later without major redesigning.)
UncleBens
Of course, this doesn't mean "Do not optimize"...
Gab Royer