Two versions of code with a slight difference. One is faster, but why?

Cosmos75

Registered User.
Local time
Today, 13:35
Joined
Apr 22, 2002
Messages
1,281
I have two versions of code with a one difference. Below are the only lines of code that are different.
Code:
[COLOR=Green]'-----------------FAST-----------------[/COLOR]
Xmultiple = 0
M = Limit ^ (i - 1)
While Xcurrent  > G
    Xmultiple = Xmultiple + 1
    Xcurrent  = Xcurrent  - (M)
Wend

[COLOR=Green]'-----------------SLOW-----------------[/COLOR]
M = Limit ^ (i - 1)
Xmultiple = (Xcurrent  - G) / M
Xmultiple = CInt(Xmultiple + 0.5) [COLOR=Green]'RoundUP to 0 decimals[/COLOR]
Xcurrent  = (Xcurrent  - (Xmultiple * M))
Why is the second version slower?
:confused:

The faster version takes anywhere from 66% to 91% of the time the slower version takes to run (based on the total time it took to run several thousand test runs, which I did several times).

One more piece of info on the code that may or may not be useful.
- “Xmultiple ” will never be more than "Limit", therefore the number of times the faster code will loop though the While statement will also never be more than the value of "Limit".
 
Last edited:
I hope that this is not a test ;)

Couple of simple observations.
  • Less Nesting of brackets - despite having a loop, mathematics are a lot more simple.
  • No call to built in functions (CInt)

You may of already done this but explicitly defining your variables will shave off a little more time as well.
 
I concur: CInt() is the main culprit...

kh
 
Fizzoi.
Fizzio said:
I hope that this is not a test ;)
You lost me there...:confused:
Fizzio said:
Couple of simple observations.
  • Less Nesting of brackets - despite having a loop, mathematics are a lot more simple.
  • No call to built in functions (CInt)
My thanks to you for clearing that up for me! :)
Fizzio said:
You may of already done this but explicitly defining your variables will shave off a little more time as well.
Yes, I did do that. And I'll admit that I sometimes forget but I am trying to get in the habit of using Option Explicit to help remind me to declare all my variables. :p
 

Users who are viewing this thread

Back
Top Bottom