Fastest way to zero a vector?

M

Mark P

Victor said:
Joseph said:
Victor Bazarov wrote:

How about

memset(&bob, 0, N*sizeof(bob));

for built-in types (or any PODs for that matter)? You can't do it
with non-PODs, however.





Forgive my ignorance; What's a POD?



It's a TLA. And it's in the FAQ. Please read the FAQ before posting.


What's a TLA? (I checked the FAQ too)
 
C

cadull

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
 
M

Mark P

Maett said:
You can ask google with "define: tla"

Maett

Neat. I had tried google before eventually figuring it out on my own,
but didn't know about the define: command and received unhelpful results.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,951
Messages
2,570,113
Members
46,698
Latest member
alexxx

Latest Threads

Top