Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is faster? "vector of structs" or "a number of vectors"?

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!

like image 677
James Bond Avatar asked Sep 01 '11 17:09

James Bond


People also ask

Which is faster vector or array?

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.

Are vectors faster than lists?

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.

How does vector increase its size?

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.

Does vector take more memory than array?

Vectors are efficient and flexible. They do require a little more memory than arrays, but this tradeoff is almost always worth the benefits.


1 Answers

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.

like image 156
Xeo Avatar answered Oct 09 '22 21:10

Xeo