MathIsNice1729
MathIsNice1729

Reputation: 242

Dynamic arrays vs. std::vector

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. 😊

Upvotes: 0

Views: 1415

Answers (2)

kjpus
kjpus

Reputation: 577

For your purpose, vector might be better, so that you don't need to worry about memory management (e.g. grow your array size and copy previous results), or reserve too much memory to store your results.

Upvotes: 1

JesseTG
JesseTG

Reputation: 2123

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).

Upvotes: 1

Related Questions