> b) for (int j=0; j<n; j++){
But your code still reads the member function every time.
1 2 3
|
int i=0, n=prices.size();
for (int j=0; j<prices.size(); j++){
|
You also need to be mindful of "debug" vs "release" builds.
In debug builds, the compiler pretty much does what you ask, and
j<prices.size() is likely to be evaluated in its entirety every time.
In release builds, the compiler will easily see that the size of prices is invariant, compute
prices.size() only once, and produce much better code.
Be wary of second guessing how the compiler works to chase that last mS.
1 2 3 4 5 6 7 8
|
int i=0, n=prices.size();
for (int j=0; j<n; j++){
// code
// then in a later edit, you add this
prices.push_back(somevalue); //!! oops, you broke the invariant.
}
|
Now your 'carefully' optimised code is suddenly broken, but it could be a while before you figure out why.
> I'm starting to pay attention to run-time and thinking about how to write more efficient codes.
The really big efficiencies come from choosing the best algorithms, not micro-managing the source code.