IGNORED

# Which is better? a = a * 2 or a = a + a?

## Recommended Posts

If 'a' starts out with a value of one, a = a * 2 would give you the same thing as a = a + a, right? So which one is faster or uses less code (or both)?

##### Share on other sites

When I run both through the Routine Size Comparison Template, the a = a + a section gives a 7, and the a = a * 2 section gives a 5. The multiplication version uses less space. How do we figure out which one is faster?

##### Share on other sites

What was the value of 'a' and why the two different results? I would assume a = a + a is faster as it's addition however i could be wrong. Interested to see the results

##### Share on other sites

Shifting is faster for powers of two. I don't know BB syntax but something like a<<=1, or a = a<<1

• 2
• 1
##### Share on other sites

From what im reading on Stackoverflow Andrew is correct for languages like C. However they also say the compiler has an optimizer that makes a decision as to what is the fastest possible way no matter how it's coded. The next question i have, does bB have such an optimizer or is that a C only feature?

##### Share on other sites

1 hour ago, TwentySixHundred said:

From what im reading on Stackoverflow Andrew is correct for languages like C. However they also say the compiler has an optimizer that makes a decision as to what is the fastest possible way no matter how it's coded. The next question i have, does bB have such an optimizer or is that a C only feature?

bB does have an optimizer, but it isn't advanced enough to know that a+a is the same as a*2. Its purpose is to remove redundant code.

That said, yes, a=a*2 is faster and uses less space than a=a+a. The reason is because for A*2, you can just issue a single ASL instruction and A+A requires a CLC and an ADC instruction.

• 1
• 2
##### Share on other sites

30 minutes ago, batari said:

bB does have an optimizer, but it isn't advanced enough to know that a+a is the same as a*2. Its purpose is to remove redundant code.

That said, yes, a=a*2 is faster and uses less space than a=a+a. The reason is because for A*2, you can just issue a single ASL instruction and A+A requires a CLC and an ADC instruction.

Thanks for clearing that up and it makes sense now how you have explained it. Some useful information about bB's optimizer ?

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.