C++ most efficient way to convert string to int (faster than atoi)

后端 未结 10 954
遥遥无期
遥遥无期 2020-12-04 17:04

As mentioned in the title, I\'m looking for something that can give me more performance than atoi. Presently, the fastest way I know is

atoi(mystring.c_str(         


        
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 17:24

    Here's the entirety of the atoi function in gcc:

    long atoi(const char *str)
    {
        long num = 0;
        int neg = 0;
        while (isspace(*str)) str++;
        if (*str == '-')
        {
            neg=1;
            str++;
        }
        while (isdigit(*str))
        {
            num = 10*num + (*str - '0');
            str++;
        }
        if (neg)
            num = -num;
        return num;
     }
    

    The whitespace and negative check are superfluous in your case, but also only use nanoseconds.

    isdigit is almost certainly inlined, so that's not costing you any time.

    I really don't see room for improvement here.

提交回复
热议问题