Simple efficiency question

I'm doing a simple addition with string. Which one is more efficient:
In the first one, the program will do short jump.
For the second, program may access carry 2 times.

1
2
3
4
if (r >= 10) {
  carry = (r-r%10)/10;
  r = r%10;
} else carry = 0;


or:

1
2
3
4
5
carry = 0;
if (r >= 10) {
  carry = (r-r%10)/10;
  r = r%10;
}


Currently I'm using the first code.
Last edited on
They are both equal. In both case it will have to test if the statement is true.
I know the result are equal. I want to make sure, which one is *REALLY efficient?

*In terms of processor usage, memory access, etc... Since this code may repeat thousand times... ^^

** BTW, I've done addition, subtraction and multiplication. The division is too hard. Maybe 2 more days...
Last edited on
Personally I would have just done:
1
2
    carry = r/10;
    r %= 10;
and had done with it.

But I'm sure, some of the more knowledgeable programmers here will be able to give you advice on profiling/optimisation techniques and tools.


Last edited on
Ah, you were right guestgulkan!
Just realized: the maximum number in 2 numbers addition is 19, so the maximum carry should only be one. I have carry in integer so the decimal should automatically truncated...

Thank you so much.

*I've tried bool for carry and the code still works.
Another question. Which one is more efficient (now should be in memory access):
1
2
3
4
5
6
7
8
for (int j=a.size()-1; j>0; j--) { // my current code
    if (a[j] == '.') continue;

    short r = (a[j] - '0') * (b[i] - '0') + carry; // declaration inside the loop
    carry = r/10;
    r %= 10;
    temp += r + '0';
}

or
1
2
3
4
5
6
7
8
9
short r = 0; // declaration outside the loop
for (int j=a.size()-1; j>0; j--) {
    if (a[j] == '.') continue;

    r = (a[j] - '0') * (b[i] - '0') + carry; 
    carry = r/10;
    r %= 10;
    temp += r + '0';
}

Or maybe there are any something simpler?
Can I just use char? Since the maximum number of multiplication should only
9 * 9 + 8 < 127 (2 numbers + carry)
Last edited on
Topic archived. No new replies allowed.