Solution 1: If i have a class like,
class car{ public: int a; string b; bool c;};
i can build a vector of 200 cars:
std::vector<car> allcas;
allcars.resize(200)
at runtime, i just do:
this_car=allcars[102];
then ....
Solution 2:
i have
std::vector<int> a; a.resize(200);
std::vector<string>b; b.resize(200);
std::vector<bool> c; c.resize(200);
this_car_a = a[102];
this_car_b = b[102];
this_car_c = c[102];
Question: Which one is faster?
Does anyone have an idea? thanks a lot in advance!
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
std::vector is insanely faster than std::list to find an element. std::vector performs always faster than std::list with very small data. std::vector is always faster to push elements at the back than std::list.
Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. The function alters the container's content in actual by inserting or deleting the elements from it.
Vectors are efficient and flexible. They do require a little more memory than arrays, but this tradeoff is almost always worth the benefits.
If a
, b
and c
belong together and form an object together, why the hell would you split them? Go for clarity and readability first. Anything else comes after that. Also, I think v2 would be slower. More access on the vector. Didn't time it though. As always for questions about speed, time it.
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