I have a class which has to store 4 floats. Is it more efficient to store the floats in an array or as 4 members of the class? Especially in combination with stl-containers and parameter passing.
-
2Measure it. Actually, don't because it won't make any noticeable difference to speed. – chris Sep 09 '13 at 17:16
-
11What matters more is how you want to use the values and how they relate to one another. Performance differences otherwise are negligible. – lurker Sep 09 '13 at 17:16
-
Both are just an offset from a memory location... – user7116 Sep 09 '13 at 17:22
-
This question is not about the *`best way to handle floating points`* but about the best way to **store floating point values**, whereas it's absolutely unclear for what purpose (as for the *handling* part). – Wolf Feb 17 '17 at 11:58
-
It depends on how you access them. Efficiency likely does not matter. – Feb 17 '17 at 17:09
7 Answers
There is unlikely to be any difference whatsoever. The memory layout will be exactly the same with both class structures; as such, most of the generated code will be the same as well (and, consequently, the performance will be the same).
The only difference I can see between the two options is that you can index into the floats if they're stored as an array. Depending on how you plan on using them, this may or may not be useful.
-
1You list a pro for the array, but not the separate floats. Pro: If they aren't in an array you can easily access them by name. – Mooing Duck Sep 09 '13 at 19:03
This smells strongly of premature optimization. Instead, name the floats meaningfully in relation to their purpose. Are they four unrelated value? Make them individual attributes. Are they four sequenced values? Make it an array. The actual performance different should be negligible if at all.

- 95,107
- 10
- 109
- 188
-
Its a bit of premature optimization. But i asked myself the question whether it is rewarding. – Hymir Sep 09 '13 at 17:41
Formally it depends on the compiler, but speed and size should be the same.
A global array indexed with a constant is for the compiler exactly the same thing as a global variable: both of them translate to just a static address in memory.
A member array indexed with a constant is exactly the same thing as a member variable: both of them translate to a an address at a fixed offset from this
.
Also g++ for sure (but most probably other compilers are too) is able to merge a copy of multiple adjacent variables with a single memory operation using larger registers.
However the question is: are the floats logically an array or four independent values?
In other words, will you ever need v[i]
where i
is a variable? If you do, then using four members will be annoying because it will require a switch
, if you never need it instead, it will be annoying to use v[0]
instead of x
.
-
The floats belonging together logically. I was wondering especially about the handling with stl-containers. When i have something like that:
std::vectorvec (10000); – Hymir Sep 09 '13 at 17:57
generate (vec.begin(), vec.end(), [&]()->ClassA{
ClassA tmp(0,0,0,0);
return tmp;
});
is it better to use an array for the swap operator for instance? -
I've read somewhere that compilers tend to have an optimization routine that inlines all iterations of fixed length <= 4. In this light it does not really matter how you store them. You ask about "parameter passing". In that case, if you'd like to pass them all together to some routine then it is handier to have them all in a fixed size array. If you make them an array you can always add some getters/setters to both the array as a whole and to each value.

- 103
- 2
- 7
You could store the floats inside an array and offer named accessors. Best of both worlds ;)
struct Vector4f
{
float a[4];
float x() const { return a[0]; }
float y() const { return a[1]; }
float z() const { return a[2]; }
float w() const { return a[3]; }
};

- 256,549
- 94
- 388
- 662
-
`Best of both worlds ;)` -- definitely no. It's just a maintenance nightmare. At best a joke, but dangerous when answered to a beginner's question. If you really think you need it, think again... – Wolf Feb 16 '17 at 11:30
Please consider this caution from the C++ FAQ: Arrays Are Evil. The final paragraph:
To net this out, arrays really are evil. You may not think so if you're new to C++. But after you write a big pile of code that uses arrays (especially if you make your code leak-proof and exception-safe), you'll learn — the hard way. Or you'll learn the easy way by believing those who've already done things like that. The choice is yours.
EDIT: After seeing the comment from @Eric, I investigated and found this insightful question: Should arrays be used in C++?. Some of the answers there indicate that declaring a member variable as a fixed-sized array can indeed be an appropriate use of an array in C++.
Generally speaking, though, as the C++ FAQ asserts, arrays should be used with caution in C++.
-
1
-
I read that link. In short he was very biassed, trying to prove that in every case one should use container classes and nothing else. Thank God such people are not in the C++ review committee and only maintain their pathetic websites! – Simple Fellow Sep 13 '13 at 13:16
-
@Simple Fellow - You might want to read [what others on SO have said about the C++ FAQ Lite](http://stackoverflow.com/search?tab=votes&q=[c%2b%2b]%20faq%20lite). Most comments I have seen have been quite positive; [for example](http://stackoverflow.com/a/2963051/1497596). That said, I'd certainly be receptive to reading what detractors of the C++ FAQ Lite have written. – DavidRR Sep 13 '13 at 21:04
-
@Simple Fellow - Also notice that the [change history for the C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/recent-changes.html) dates back to 1994. And that the author [welcomes contributions from others](http://www.parashift.com/c++-faq-lite/please-send-material.html). – DavidRR Sep 13 '13 at 21:21
-
As much as I know, accessing 4 floats in an array is faster than 4 instance variables declared in the class.
The code generated by C++ compilers for arrays uses indexed addressing mode which is easier and faster for intel processors.
I've worked on OpenGL for 3D graphics a long time ago. The functions were either able to take a vertex either as x, y, z values, vertex structures or an array of float with 3 members. The functions which required arrays were faster than their counterparts.
The speed would also depends on what kind of calculations would you be performing.
You haven't mentioned much about the design or domain but also check also if it makes more sense to store them in an array or instance variable. Remember that optimized code comes at the price of reduced readability and sometimes maintenance issues.

- 4,315
- 2
- 31
- 44
-
5
-
I compiled code using Apple LLVM 5.0 that accessed a struct with an array of four `float` using `x->f[2]` and other code that accessed a struct with four separate members using `x->c`. In both cases, the generated assembly code used `8(%rdi)` to refer to the member. In fact, the implementation of code that accesses individual members is inherently a subset of code that accesses array elements, since any reference to `.MemberName` in a struct of individual members is equivalent to some `.Array[Index]` in a struct with an array. (The converse is not true since an index may be non-constant.) – Eric Postpischil Sep 09 '13 at 23:51
-
Not every compiler generates the exact same instructions and performs same optimizations. "All compilers are not equal" otherwise how is it possible to have a faster exe from an intel compiler than VC and C++ builder compiler from the same code? – Simple Fellow Sep 13 '13 at 13:08
-
@Hymir I read your question again and my answer. I missed teh last line "Especially in combination with stl-containers and parameter passing" The simple answer is Yes, they are faster when passed as parameter and stl container can handle them well. since its a comment i cannot write details here but "Yes" is the answer. Now please mark mark my answer as the best answer! :) – Simple Fellow Sep 13 '13 at 13:26
-
1The question is about an array member vs separate members. Your experience which you mention is with function parameters, which is not at all the same thing. There shouldn't be a difference with member vairables. – interjay Feb 17 '17 at 11:34
-
I think your core statement ***`accessing 4 floats in an array is faster than 4 instance variables`*** is misleading, and most probably just wrong. Also the idea of taking advantage of old experiences (*`I've worked on OpenGL for 3D graphics a long time ago`*) seems a bad one when discussing efficiency of compiled code. But well, without the emphasis of your oversimplified conclusion, I'd see a valuable contribution in this answer. – Wolf Feb 17 '17 at 11:42