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

后端 未结 10 971
遥遥无期
遥遥无期 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 17:30

    This page compares conversion speed between different string->int functions using different compilers. The naive function, which offers no error checking, offers speeds roughly twice as fast as atoi(), according to the results presented.

    // Taken from http://tinodidriksen.com/uploads/code/cpp/speed-string-to-int.cpp
    int naive(const char *p) {
        int x = 0;
        bool neg = false;
        if (*p == '-') {
            neg = true;
            ++p;
        }
        while (*p >= '0' && *p <= '9') {
            x = (x*10) + (*p - '0');
            ++p;
        }
        if (neg) {
            x = -x;
        }
        return x;
    }
    

    it is always positive

    Remove the negative checks in the above code for a micro optimization.

    If you can guarantee the string will not have anything but numeric characters, you can micro optimize further by changing the loop

    while (*p >= '0' && *p <= '9') {
    

    to

    while (*p != '\0' ) {
    

    Which leaves you with

    unsigned int naive(const char *p) {
        unsigned int x = 0;
        while (*p != '\0') {
            x = (x*10) + (*p - '0');
            ++p;
        }
        return x;
    }
    

提交回复
热议问题