Reputation: 789
I noticed that other students like to use a lot of arrays for elements of what really should be fields of some object.
Is this because it is faster to access an element from an array vs a field from a structure?
For example, say I have clock cycles stored for some object as...
1) An array of 5 ints
2) As a field in 5 structures
And I then need to access these elements to find min / max.
I like the idea of keeping properties of some object together as opposed to having multiple arrays for what would have fit naturally as a field. I'm just not sure if I'm writing what would be considered bad programming habits by handling it as a field in a structure.
Upvotes: 1
Views: 51
Reputation: 28251
Maybe not with 5 elements - but with thousands of elements, there might be a difference.
The universal principle of caching is Locality of reference - it's better to store stuff together. If you know that your program will access only one (or a few) field of your structures, it's better to relocate that field into a dedicated array. If your program accesses all (or most) fields of your structures, it's better to hold the structures themselves in an array.
However, like everything related to performance, the real behavior is frequently surprising, and you usually have to measure one way of implementation, then the other, and choose the best.
If your application doesn't require performance optimization, just use code that is most readable. It may allocate your "clock cycles" as a field in a struct
or as an array - which way is more readable depends on your application. And sometimes even on which aspect of the application you are currently developing.
Upvotes: 5
Reputation: 31465
I very much doubt it matters - performance wise - in any measurable way.
But if in doubt, why don't you benchmark it?
Upvotes: 1