Given:
void foo(std::vector<int> v);
void bar()
{
std::vector<int> v = ...; // many items
foo(v);
}
What in a profiling tool would show as the hot path? Would it be the std::vector<T>
's copy constructor, the runtime or the operating system? I remember in school (I'm not a C++ dev, just work with some) that this will copy v
and that can take time. I do know that a signature like:
void foo(const std::vector<int>& v);
avoids this potentially costly copy operation.
Copying std::vector<T>
by value does, potentially, three things:
new
with copy c-tor for each element in the new vector if T
is not trivially copy-constructible. Otherwise, memcpy()
or it's optimized vectorized (in sse
sense) counterpart is called. Just before the first time the new memory is written, if it was acquired from the OS in #2, the OS will need to actually allocate the new VM page and that may trigger RAM access (hardware), TLB lookup (hardware + OS) swapping in/out (OS).In your specific example T
is trivially copy-constructible so the worst case overhead would be C++
runtime memory block lookup + sbrk()
syscall + memcpy()
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With