vendredi 21 juin 2019

Performance issue of std::move for different length of std::string

I recently noticed that std::move for std::string in my program is somehow slower than direct copy assignment.

For example,

#include <string>
#include <vector>                                                                                                                          
#include <chrono>
#include <iostream>

int main(int argc, char *argv[])
{
    size_t len(atoi(argv[1]));
    std::string str, tmp;
    std::vector<std::string> v(1000000);

    for (auto& i : v)
    { 
        i.reserve(len);
        for (size_t j(0); j < len; j++)
            i.push_back('0' + (j % 10));
    } 

    str.reserve(len);

    std::chrono::duration<double, std::milli> d;
    auto c(std::chrono::steady_clock::now());

    for (size_t i(0); i < v.size(); i++)
    { 
        //str = v[i]; // copy assignment
        str = std::move(v[i]); // move
    } 

    d = std::chrono::steady_clock::now() - c;
    std::cout << d.count() << "ms\n";
} 

And I compiled it by: g++-8 -std=c++17 -o test test.cpp

Here are some test results:

short string(10bytes) * 1000000
    -O0:
        copy: ~60ms
        move: ~100ms
    -O3:
        copy: ~8.4ms
        move: ~7.5ms

short string(100bytes) * 1000000
    -O0:
        copy: ~64ms
        move: ~110ms
    -O3:
        copy: ~9.4ms
        move: ~15ms

long string(1000bytes) * 1000000
    -O0:
        copy: ~190ms
        move: ~107ms
    -O3:
        copy: ~107ms
        move: ~16ms

There are some points make me confused.

  1. Why 10bytes string has the same speed with 100bytes string if no optimization is used?

  2. Why copy is faster than move without optimization most of the time?

  3. Why O3 makes less speedup for copying 1000bytes string?

Aucun commentaire:

Enregistrer un commentaire