I have recently started relearning C++ as I have not been coding in C++ for more than a decade. I have rarely used the STL, even when I worked at SGI, and I want to master it. I have ordered a book and I am currently running different online tutorials.
One tutorial introduced std::find(begin(),end(),value) and I was shocked at how slow it was in the test code I wrote. After doing some trial and error I found that s.find(value) was clearly what I should be using.
Why is the first find in the code so dramatically slow?
set<int> s;
for (int i = 0; i < 100000; i++)
s.insert(rand());
for (int i = 0; i < 10000; i++) {
int r = rand();
//first find is about 1000x slower than the next one
auto iter1 = std::find(s.begin(), s.end(), r);
auto iter2 = s.find(r);
}
EDIT: added timing experiment results
@juanchopanza asked about timing in the comments so I timed std::find() on Set, List, Vector and set.find()
(I only measured find - variation between runs was below 10%)
Vector performs much better than List or Set, but the specialized find from set wins with big data sets.
Elements Vector List Set | Set.Find()
10 0.0017 0.0017 0.0020 | 0.0017
100 0.0028 0.0051 0.0120 | 0.0019
1000 0.0105 0.0808 0.1495 | 0.0035
10000 0.0767 0.7486 2.7009 | 0.0068
100000 0.2572 2.4700 6.9636 | 0.0080
1000000 0.2674 2.5922 7.0149 | 0.0082
10000000 0.2728 2.6485 7.0833 | 0.0082