In a piece of code I'm working on, I end up resetting a "large-ish" vector. I'm wondering what the best way to do this would be. Looping over index? Over iterators? Or copying a new vector?
One of the vectors is a vector of bools, which is a specialized template. Does it change the answer?
I tried testing it, but I'm having troubles finding a proper test that isn't skewed by some behind-the-scenes optimizations.
[edit]
Probably taking it a bit too far, but in the case of the bools: if I reset to "true", would it be faster to ' = true', or to OR with 1?
Error: Memset not defined in this scope. Need to add <cstring> to includes.
Also memset looks the faster on C::B / XP, like half the time the other functions take.
Ran this on an XP Pro (x86) workstation with C::B with these results:
1 2 3 4 5 6 7
CPU time used by memset = 15
CPU time used by assign = 63
CPU time used by for loop = 93
CPU time used by just making another vector = 63
Process returned 0 (0x0) execution time : 0.390 s
Press any key to continue.
@Moschops : Actually half, but didn't take a indeep-closeAllPrograms-OverclockPC test.
@Cubbi : Maybe you devided by CLOCKS_PER_SEC and you stored the result into an integer? Dunno, I get readable results.
@Gaminic I'm going to guess that your C++ library implements vector.assign as a call to memset() for suitable value_type (which is a very common implementation technique), and that you library memset() is too generic to make use of platform-specific optimizations, while your C++ compiler is set to optimize. (linux has the same problem, memset() and other general-purpose precompiled C library functions are slower than loops optimized to the target architecture)