Re: suggestion for pre-c++11 two item container compatible with vector?
On Tuesday, June 4, 2013 6:17:13 PM UTC+1, Paavo Helde wrote:
Shriramana Sharma <samjnaa@gmail.com> wrote in
news:56384363-c683-4de1-b3dd-35a26429f549@googlegroups.com:
Hello. In my app I am having to return short arrays of doubles
frequently from utility functions, the max length being 2. I am
concerned whether using vector would involve excessive memory usage
and unneeded copying at function return.
It would have to be a container type compatible with vector in the
sense of providing [] access and compatible with the algorithms
applicable to containers and so std::pair is not feasible.
In C++11 I suppose I could use array, but that's not an option for me
because I don't want to require C++11 support on my users' compilers.
(It's open-source and people with old compilers should be able to
compile it.)
Should I just roll my own simple class or can I just re-use vector
confident that it won't use too much memory?
You can measure sizeof(std::vector<double>) easily yourself. It is
probably much more than 2*sizeof(double) (in my compiler it is 40 bytes,
plus the 2-double array is probably allocated dynamically, probably
meaning another 40 bytes or so) (and the dynamic allocation/deallocation
probably causes the largest performance hit here).
If debugging isn't active, the sizeof a vector will almost
certainly be 3 * sizeof(T*). 12 on a 32 bit implementation, 24
on a 64 bit machine. However...
Does it matter? It depends. How many of those objects you are passing
aroud? Are the copies optimized away by RVO?
If the number of those objects is in tens or hundreds, you shouldn't
worry. If there are millions of those passed around, then yes, I would
feel a quite strong desire to write my own class with minimal needed
interface. But actually one should profile first and see if this is a
bottleneck or not.
That's the only correct answer. If std::vector provides the
desired interface, then the only reason to use something else is
that the profiler says you must.
On the other hand, does it really make sense to provide an
array-like interface when there can be a maximum of two
elements?
--
James