Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of these codes will run faster

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.

like image 526
Skeith Avatar asked Apr 13 '11 09:04

Skeith


People also ask

What makes code run faster?

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.

What type of code is executed run faster?

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.

What is faster C or C++?

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.


2 Answers

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++.

like image 50
Johann Gerell Avatar answered Oct 05 '22 11:10

Johann Gerell


Your compiler will probably generate the same machine-level instructions in both cases. Don't bother.

like image 26
Jonas Bötel Avatar answered Oct 05 '22 12:10

Jonas Bötel