Reputation: 1071
Is there any difference between:
std::vector<int> B;
B.resize(N);
and
std::vector<int> B(N); //or std::vector<int> B(N,0);
or is the second method the short form of the first method?
Upvotes: 0
Views: 39
Reputation: 5251
Is there a measurable difference in performance? No, not at all.
Is there a readability difference? The allocator version is much more concise and easier to grok at a glance.
Is there a difference in the generated instructions? Depends on the compiler and its opts. Let's take a look with gcc:
int main() {
std::vector<int> B(1);
}
compiles to:
call std::allocator<int>::allocator() [complete object constructor]
lea rdx, [rbp-17]
lea rax, [rbp-48]
mov esi, 1
mov rdi, rax
call std::vector<int, std::allocator<int> >::vector(unsigned long, std::allocator<int> const&)
lea rax, [rbp-17]
mov rdi, rax
The other case:
int main() {
std::vector<int> B;
B.resize(1);
}
Compiles to:
call std::vector<int, std::allocator<int> >::vector() [complete object constructor]
lea rax, [rbp-48]
mov esi, 1
mov rdi, rax
call std::vector<int, std::allocator<int> >::resize(unsigned long)
lea rax, [rbp-48]
mov rdi, rax
They are very very similar. The difference is negligible. Only difference here is the allocator version has an additional LEA instruction for loading std::allocator
(LEA does memory addressing calculations, but doesn't actually address memory.) Optimizer fudge.
Bear in mind, compiler optimizations are not standard. As far as the language itself dictates, there would be no difference between these two calls at all.
Upvotes: 2