Sign in to follow this  
leiavoia

Simple Loop Question

Recommended Posts

Here is a simple loop
for (int i = 0; i < GetSomeNumber(); i++) { }
Question: is GetSomeNumber() called every trip through the loop or is it called once and compared against on every iteration? If it gets called every time, i could certainly optimize a lot of code with a simple caching beforehand:
int limit = GetSomeNumber();
for (int i = 0; i < limit; i++) { }

Share this post


Link to post
Share on other sites
It depends on the details. If the compiler can determine that the function will always return the same number inside the loop, then it will be optimized away. Different compilers can make such determinations with different levels of success. When in doubt, turn on the 'generate assembly output' option for your compiler and check to see if it calls the function each iteration.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this