Std :: vector optimization

Assuming a loop that reads a lot of values ​​from std :: vector is a bottleneck in my program, it was suggested to change

void f(std::vector<int> v)
{
    ...
    while (...)
    {
        ...
        int x = v[i] + v[j]
        ...
    }
}

to

void f(std::vector<int> v)
{
    int* p_v = &v[0];
    ...
    while (...)
    {
        ...
        int x = p_v[i] + p_v[j]
        ...
    }
}

Will this actually improve performance by traversing the [] operator?

+3
source share
5 answers

Most likely (at first glance) that copying the entire vector every time you call this function is a bottleneck. Why instead?

void f(const std::vector<int>& v)

In any case, never guess where the bottleneck is - first measure and set up a code that slows down as soon as you know for sure.

+26
source

No, this should not affect performance.

, , , pass-by-reference-to-const pass-by-value .

EDIT: , . @Steve Townsend.

+15

, . () . , , operator[] .

, . , .

+4

, , , , , . , , . , , , . ( , , , , ), , . , , - ( ), , , .

+3
source

If you only need sequential access to the contents of the vector (and, unfortunately, your example seems to show random access, so this will not work, but maybe this is just an example), you can achieve significant speed improvements using iterators for moving vector. I saw that this optimization makes a noticeable difference even on simple arrays with compiler optimization turned on.

0
source

Source: https://habr.com/ru/post/1762888/


All Articles