I've written a small program to calculate prime numbers using the naive division algorithm. In order to improve the performance, I thought it should only check the divisibility based on previously detected primes less than equal to the number's square root.
In order to do that, I need to keep track of the primes. I've implemented it using dynamic arrays. (e.g. Using new
and delete
). Should I use std::vector
instead? Which is better in terms of performance? (Maintenance is not an issue.)
Any help would be appreciated. 😊
The ideal answer:
How should any of us know? It depends on your compiler, your OS, your architecture, your standard library implementation, the alignment of the planets...
Benchmark it. Possibly with this. (Haven't used it, but it seems simple enough to use.)
The practical answer:
Use std::vector
. Every new
and delete
you make is a chance for a memory leak, or a double-delete
, or otherwise forgetting to do something. std::vector
basically does this under the hood anyway. You're more likely to get a sizeable performance boost by maxing out your optimization flags (if you're using gcc
, try -Ofast
and -march=native
).
Also:
Maintenance is not an issue.
Doubt it. Trust me on this one. If nothing else, at least comment your code (but that's another can of worms).