Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficiency of manually written loops vs operator overloads
    text
    copied!<p>in the program I'm working on I have 3-element arrays, which I use as mathematical vectors for all intents and purposes. </p> <p>Through the course of writing my code, I was tempted to just roll my own <code>Vector</code> class with simple arithmetic overloads (<code>+, -, * /</code>) so I can simplify statements like:</p> <pre><code>// old: for (int i = 0; i &lt; 3; i++) r[i] = r1[i] - r2[i]; // new: r = r1 - r2; </code></pre> <p>Which should be more or less identical in generated code. But when it comes to more complicated things, could this really impact my performance heavily? One example that I have in my code is this:</p> <p>Manually written version:</p> <pre><code>for (int j = 0; j &lt; 3; j++) { p.vel[j] = p.oldVel[j] + (p.oldAcc[j] + p.acc[j]) * dt2 + (p.oldJerk[j] - p.jerk[j]) * dt12; p.pos[j] = p.oldPos[j] + (p.oldVel[j] + p.vel[j]) * dt2 + (p.oldAcc[j] - p.acc[j]) * dt12; } </code></pre> <p>Using the <code>Vector</code> class with operator overloads:</p> <pre><code>p.vel = p.oldVel + (p.oldAcc + p.acc) * dt2 + (p.oldJerk - p.jerk) * dt12; p.pos = p.oldPos + (p.oldVel + p.vel) * dt2 + (p.oldAcc - p.acc) * dt12; </code></pre> <p>I am attempting to optimize my code for speed, since this sort of code runs inside of inner loops. Will using the overloaded operators for these things affect performance? I'm doing some numerical integration of a system of n mutually gravitating bodies. These vector operations are extremely common so having this run fast is important.</p> <p>Any insight would be appreciated, as would any idioms or tricks I'm unaware of.</p>
 

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