Joseph said:
I have a vector<bool> of fixed size N. Let's call it bob.
I'm zero'ing bob quite a bit, i.e.:
bob = vector<bool>(N, false);
Naturally, this is quite slow, because of all the object creation.
Can I do any better than the following:
bob.clear(); bob.resize(N, false);
?
I don't mind changing the container type or the entry type (e.g.
bool->char), so if you have any suggestions in that vein then fire
away.
Since N<=3 how about storing within a larger POD type? e.g.
// implementation
typedef int FullBob;
typedef bool BoolBob[4];
// spare entries not used (could store N if required)
inline void ZeroBob(BoolBob& bob)
{
reinterpret_cast<FullBob&>(bob) = 0;
}
// compile time size validation
template<bool test> inline bool CheckBob()
{
return true;
}
template<> inline bool CheckBob<false>()
{
// no return value
}
int main()
{
CheckBob<sizeof(BoolBob)==sizeof(FullBob)>();
// example usage
BoolBob bob;
ZeroBob(bob);
bob[0] = true;
}
Having bob aligned in memory (e.g. choose FullBob type to be 32 bit on 32
bit architechure) may provide a benefit provided the extra memory usage (if
many bob's exist) isn't an issue.
There are plenty of alternative implemention methods of the above idea (e.g.
unions, custom class). A union might provide more reliable memory alignment.
I'm trying to get this to be really fast, so I'll entertain any
so-called "extreme solution".
To really guage performance you'll need to time various implementations as
they would typically be used. If this really is a bottleneck in a slowly
performing application then I'd suggest that a redesign at a higher level
would be more beneficial.
Regards,
cadull