which is faster? returning a new vector or passing the vector ref

I guess I am more interested in speed, as if i wanted anything else i would just use Python's built-in str.split() method. I sat here debating to myself which would be better suited for speed. Its seems at first the one using a reference would be faster, but then its only being passed in "always" an empty vector. But then the returning one doesnt have to take in the vector, so then maybe that one would be faster.

I guess the only method would be to take a long string a test them. But i am not sure how to self test time. I could use Bash's time to test it, but it seems weird to rely on it when programming. I might as well learn how to self test in c++ also.

Or is this such a small difference that either or is decent?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void split(const std::string &str, std::vector<std::string> &v) {
    std::stringstream ss(str);
    ss >> std::noskipws;
    std::string field;
    char ws_delim;
    while(true) {
        if( ss >> field )
            v.push_back(field);
        else if (ss.eof())
            break;
        ss.clear();
        ss >> ws_delim;
    }
}

std::vector<std::string> split2(const std::string &str) {
    std::stringstream ss(str);
    std::vector<std::string> v;
    ss >> std::noskipws;
    std::string field;
    char ws_delim;
    while(true) {
        if( ss >> field )
            v.push_back(field);
        else if (ss.eof())
            break;
        ss.clear();
        ss >> ws_delim;
    }
    return v;
}


Does those in C++ try to avoid using return as for to get a speed boost?
Last edited on
Does those in C++ try to avoid using return as for to get a speed boost?


Not generally, no.

Google "RVO", "NRVO", "move semantics"
Topic archived. No new replies allowed.