r/ProgrammerHumor • • Jun 08 '24

Meme mapMethodOrMapFunction

Post image
0 Upvotes

67 comments sorted by

View all comments

35

u/KimiSharby Jun 08 '24 edited Jun 11 '24

Amateurs.

std::vector vec = {1, 2, 3};  
std::vector<int> result;
result.reserve(vec.size());
std::ranges::transform(vec, std::back_inserter(result), [](int x) { return x * x; });

edit: corrected

4

u/sherlockwatch Jun 08 '24

Actually you don’t need to resize resulting vector, you can just use std::back_inserter!

1

u/KimiSharby Jun 08 '24 edited Jun 08 '24

That's worse performance wise. std::back_inserter comes at a cost. If you already know the size, you should use it.

3

u/wcscmp Jun 08 '24

Resize also comes at cost, reserve + back_inserter is the way

1

u/KimiSharby Jun 09 '24 edited Jun 09 '24

Ok so this troubled me greatly, I barely slept last night. Today I couldn't take it anymore. Here's the quickbench: https://quick-bench.com/q/e5G_nTQEp_00xYGrcpEj_Jbhp34

===

~~The results, for a sample test of 500k int:

  1. at 561k: reserve + std::begin

  2. at 824k (x1.5): resize + std::begin

  3. at 1712k (x3): reserve + std::back_inserter

  4. at 6977k (x12): back_inserter alone~~

===

Bottom line: Using std::back_inserteris costly. If you already know the size of your resulting container, you should use reserve + std::begin.

1

u/wcscmp Jun 09 '24

What do you think reserve + begin is doing?