Note that there are some explanatory texts on larger screens.

plurals
  1. POPerformance: vector of classes or a class containing vectors
    primarykey
    data
    text
    <p>I have a class containing a number of double values. This is stored in a vector where the indices for the classes are important (they are referenced from elsewhere). The class looks something like this:</p> <h2>Vector of classes</h2> <pre><code>class A { double count; double val; double sumA; double sumB; vector&lt;double&gt; sumVectorC; vector&lt;double&gt; sumVectorD; } vector&lt;A&gt; classes(10000); </code></pre> <p>The code that needs to run as fast as possible is something like this:</p> <pre><code>vector&lt;double&gt; result(classes.size()); for(int i = 0; i &lt; classes.size(); i++) { result[i] += classes[i].sumA; vector&lt;double&gt;::iterator it = find(classes[i].sumVectorC.begin(), classes[i].sumVectorC.end(), testval); if(it != classes[i].sumVectorC.end()) result[i] += *it; } </code></pre> <p>The alternative is instead of one giant loop, split the computation into two separate loops such as:</p> <pre><code>for(int i = 0; i &lt; classes.size(); i++) { result[i] += classes[i].sumA; } for(int i = 0; i &lt; classes.size(); i++) { vector&lt;double&gt;::iterator it = find(classes[i].sumVectorC.begin(), classes[i].sumVectorC.end(), testval); if(it != classes[i].sumVectorC.end()) result[i] += *it; } </code></pre> <p>or to store each member of the class in a vector like so:</p> <h2>Class of vectors</h2> <pre><code>vector&lt;double&gt; classCounts; vector&lt;double&gt; classVal; ... vector&lt;vector&lt;double&gt; &gt; classSumVectorC; ... </code></pre> <p>and then operate as:</p> <pre><code>for(int i = 0; i &lt; classes.size(); i++) { result[i] += classCounts[i]; ... } </code></pre> <p>Which way would usually be faster (across x86/x64 platforms and compilers)? Are look-ahead and cache lines are the most important things to think about here?</p> <h2>Update</h2> <p>The reason I'm doing a linear search (i.e. find) here and not a hash map or binary search is because the sumVectors are very short, around 4 or 5 elements. Profiling showed a hash map was slower and a binary search was slightly slower.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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