Is using string.length() in loop efficient?

前端 未结 6 1942
我在风中等你
我在风中等你 2021-02-20 09:11

For example, assuming a string s is this:

for(int x = 0; x < s.length(); x++)

better than this?:

int length         


        
6条回答
  •  梦如初夏
    2021-02-20 09:52

    Although I am not necessarily encouraging you to do so, it appears it is faster to constantly call .length() than to store it in an int, surprisingly (atleast on my computer, keeping in mind that I'm using an MSI gaming laptop with i5 4th gen, but it shouldn't really affect which way is faster).

    Test code for constant call:

    #include 
    
    using namespace std;
    
    int main()
    {
        string g = "01234567890";
        for(unsigned int rep = 0; rep < 25; rep++)
        {
            g += g;
        }//for loop used to double the length 25 times.
        int a = 0;
        //int b = g.length();
        for(unsigned int rep = 0; rep < g.length(); rep++)
        {
            a++;
        }
        return a;
    }
    

    On average, this ran for 385ms according to Code::Blocks

    And here's the code that stores the length in a variable:

    #include 
    
    using namespace std;
    
    int main()
    {
        string g = "01234567890";
        for(unsigned int rep = 0; rep < 25; rep++)
        {
            g += g;
        }//for loop used to double the length 25 times.
        int a = 0;
        int b = g.length();
        for(unsigned int rep = 0; rep < b; rep++)
        {
            a++;
        }
        return a;
    }
    

    And this averaged around 420ms.

    I know this question already has an accepted answer, but there haven't been any practically tested answers, so I decided to throw my 2 cents in. I had the same question as you, but I didn't find any helpful answers here, so I ran my own experiment.

提交回复
热议问题