Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficiency of using stringstream to convert string to int?

Is the code below less (or more, or equally) efficient than:

make substring from cursor
make stringstream from substring
extract integer using stream operator

? (question edit) or is it less (or more, or equally) efficient than:

std::stoi

? and why?

Could this function be made more efficient?

(The class brings these into scope:)

std::string expression  // has some numbers and other stuff in it
int cursor              // points somewhere in the string

The code:

int Foo_Class::read_int()
{
    /** reads an integer out of the expression from the cursor */

    // make stack of digits
    std::stack<char> digits;

    while (isdigit(expression[cursor]))  // this is safe, returns false, for the end of the string (ISO/IEC 14882:2011 21.4.5)
    {
        digits.push(expression[cursor] - 48);  // convert from ascii
        ++cursor;
    }

    // add up the stack of digits
    int total = 0;
    int exponent = 0;  // 10 ^ exponent
    int this_digit;

    while (! digits.empty())
    {
        this_digit = digits.top();
        for (int i = exponent; i > 0; --i)
            this_digit *= 10;
        total += this_digit;

        ++exponent;
        digits.pop();
    }

    return total;
}

(I know it doesn't handle overflow.)

(I know someone will probably say something about the magic numbers.)

(I tried pow(10, exponent) and got incorrect results. I'm guessing because of floating point arithmetic, but not sure why because all the numbers are integers.)

like image 747
beauxq Avatar asked Sep 15 '25 20:09

beauxq


1 Answers

I find using std::stringstream to convert numbers is really quite slow.

Better to use the many dedicated number conversion functions like std::stoi, std::stol, std::stoll. Or std::strtol, std::strtoll.

like image 151
Galik Avatar answered Sep 18 '25 17:09

Galik