Why will the recursive method for converting decimal to binary be faster than iterative using return strings?

I created two functions that take a decimal number and return a binary representation of that number. I chose an easy way to do this by combining 1 and 0 into a string after some simple math. For this, I created an iterative and recursive method. Then I timed two methods with the timer class that my teacher gave me. It turned out that my recursive method was about twice as fast as compared to my iterative method. Why is this so?

string CConversion::decimalToBinaryIterative(int num)
{
   string ss;
   while(num > 0)
   {
        if  (num%2 != 0)
        {
            ss = '1' + ss;
        }
        else
        {
            ss = '0' + ss;
        }
        num=num/2;
    }
    return ss;
}
string CConversion::decimalToBinaryRecursive(int num)
{
    if(num <= 0)
    { 
        return "";
    } 
    else 
    {
       if  (num%2 != 0)
       {
            return decimalToBinaryRecursive(num/2) + '1';
       }
        else
        {
            return  decimalToBinaryRecursive(num/2) + '0';
        }
    }

}
+4
source share
2 answers

std::string , , , .

.

string ss;
while(num > 0)
{
    if  (num%2 != 0)
    {
        ss = ss + '1';
    }
    else
    {
        ss = ss + '0';
    }
    num=num/2;
 }
 return string(ss.rbegin(), ss.rend());

, .

+5

- , :

ss = ss + '1';  // 1

ss = '1' + ss;  // 2

( ) .

( ).

, ss += 'x', .

+3

All Articles