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. (eg 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).
为了您的目的,向量可能会更好,这样您就不必担心内存管理(例如,增加数组大小并复制以前的结果),或保留太多内存来存储结果。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.