I notice that vector is much slower than bool array when running the following code.
int main()
{
int count = 0;
int n = 1500000;
// slower with c++ vector<bool>
/*vector<bool> isPrime;
isPrime.reserve(n);
isPrime.assign(n, true);
*/
// faster with bool array
bool* isPrime = new bool[n];
for (int i = 0; i < n; ++i)
isPrime[i] = true;
for (int i = 2; i< n; ++i) {
if (isPrime[i])
count++;
for (int j =2; i*j < n; ++j )
isPrime[i*j] = false;
}
cout << count << endl;
return 0;
}
Is there some way that I can do to make vector<bool>
faster ? Btw, both std::vector::push_back
and std::vector::emplace_back
are even slower than std::vector::assign
.
isPrime
beyond its end, it should benew bool[n]
– Zebavector<bool>
if you're super-concerned about performance. It's required by the standard to be very space efficient, and that has a performance cost. – Baloney