I have recently begun to think about optimisation, now I know there are many books and articles but I have a particular scenario i'm interested in.
A.
for (i = 0; i < limit + 5; i++)
cout << test;
B.
limit2 = limit +5;
for (i = 0; i < limit2; i++)
cout << test;
What I want to know is would the second piece of code run faster because it only has to do the mathematical calculation once or is the calculation stored for the lifetime of the loop.
To code faster, one has to be efficient; that is, no wasted effort or motion. This can mean everything from typing to tools to thinking. But most of our work as programmers isn't typing, or compiling—it's thinking. To think faster, you have to learn more patterns and relationships.
Compiler: The compiled languages are always going to be faster than interpreted languages. The compiler compiles all of the code into executable machine code at once, whereas the interpreter scans the program line by line and converts it into machine code. So it delays the execution time for interpreters.
Execution speed - C++ is often faster than C, because templates are a better solution to generic code than C's tendency to use function pointers. See C++'s std::sort vs C's qsort for a widely benchmarked example.
Assuming that the types are simple, as in int
etc., I'd be really surprised if any decent compiler didn't optimize both examples to the same code in a release build. A complex type might for instance require more horse-power in an overloaded operator++
.
Your compiler will probably generate the same machine-level instructions in both cases. Don't bother.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With