Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically allocated arrays or std::vector
    text
    copied!<p>I'm trying to optimize my C++ code. I've searched the internet on using dynamically allocated C++ arrays vs using std::vector and have generally seen a recommendation in favor of std::vector and that the difference in performance between the two is negligible. For instance here - <a href="https://stackoverflow.com/questions/381621/using-arrays-or-stdvectors-in-c-whats-the-performance-gap">Using arrays or std::vectors in C++, what&#39;s the performance gap?</a>. </p> <p>However, I wrote some code to test the performance of iterating through an array/vector and assigning values to the elements and I generally found that using dynamically allocated arrays was nearly 3 times faster than using vectors (I did specify a size for the vectors beforehand). I used g++-4.3.2.</p> <p>However I feel that my test may have ignored issues I don't know about so I would appreciate any advice on this issue.</p> <p>Thanks</p> <p>Code used - </p> <pre><code>#include &lt;time.h&gt; #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() { clock_t start,end; std::vector&lt;int&gt; vec(9999999); std::vector&lt;int&gt;::iterator vecIt = vec.begin(); std::vector&lt;int&gt;::iterator vecEnd = vec.end(); start = clock(); for (int i = 0; vecIt != vecEnd; i++) { *(vecIt++) = i; } end = clock(); cout&lt;&lt;"vector: "&lt;&lt;(double)(end-start)/CLOCKS_PER_SEC&lt;&lt;endl; int* arr = new int[9999999]; start = clock(); for (int i = 0; i &lt; 9999999; i++) { arr[i] = i; } end = clock(); cout&lt;&lt;"array: "&lt;&lt;(double)(end-start)/CLOCKS_PER_SEC&lt;&lt;endl; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload