Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would the recursive method of converting decimal to binary be faster than the iterative, using and returning strings?

I created two functions that accept a decimal number and return the binary representation of that number. I chose a simple way to do this by concatenating on 1's and 0's to a string after some simple math. I created a iterative and recursive method to do this. Then I timed the two methods with a timer class my teacher gave me. It turned out that my recursive method was about twice as fast compared to my iterative method. Why would this be the case?

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';
        }
    }

}
like image 720
theuglymonkey Avatar asked Feb 14 '23 17:02

theuglymonkey


1 Answers

Appending a character to a std::string is cheaper than pre-pending one, because appending can be done without copying the string if string's capacity permits you to do so.

Prepending, however, always requires a copy of the entire string.

If you change your iterative code to this

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());

the timing should be nearly the same, or the iterative should become narrowly faster.

like image 197
Sergey Kalinichenko Avatar answered Apr 27 '23 23:04

Sergey Kalinichenko