Skip navigation

测试程序

#include <sys/time.h>
#include <iostream>
#include <string>

int main()
{
        struct timeval tv[2];
        struct timezone tz;

        int count = 50000;
        int elapsed = 0;

        // .. string initialization

        gettimeofday(&amp;tv[0], &amp;tz);
        while(count--) {
        // .. real action here ..
        }
        gettimeofday(&amp;tv[1], &amp;tz);

        elapsed = (tv[1].tv_sec - tv[0].tv_sec) * 1000000
                      + (tv[1].tv_usec - tv[0].tv_usec);

        std::cout << "elapsed: " << (double)elapsed / 1000 << "ms" << std::endl;
}

operator+ vs append

使用 s = “/” + t, 测试时间为 16.375ms, 但是使用 s.append(”/”).append(t) 时间是 5.528ms.

operator+ vs operator +=

使用 s = s + t, 测试时间为 5596.4ms, 而相比之下 s += t 需要 4.639ms.

结论

很明显,像书本上讲的一样,opterator + 总是会创建一个临时对象。所以,要慢很多。因此,当需要连接字符串时应该首选 ** += **.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>