celestiary / web

Astronomical simulator of solar system and local stars
https://celestiary.github.io/
42 stars 2 forks source link

Use symmetry to shorten inner loop #14

Closed won3d closed 3 years ago

won3d commented 3 years ago

https://github.com/pablo-mayrgundter/celestiary/blob/9eccfa56dace1835651ee510f705ce5f91b04ecd/js/Galaxy.js#L83-L86

The inner loop performs the same iteration as the outer loop, iterating all the points except the one where i === j. But you can exploit the symmetry between pairs of interactions: if you compute a force on i from j, then j will feel an equal but opposite force. So, the inner loop could actually be something like: for (j = 0; j < i; ...). Maybe it would even be faster to iterate the loop backwards from i for better memory locality. And then when you add in newVelos[i] make sure you subtract from newVelos[j]

pablo-mayrgundter commented 3 years ago

Fixed in https://github.com/pablo-mayrgundter/celestiary/commit/36f4387bd4d4ce08a4f5865bc1ec9e56d57b1e08#diff-1ab10843cfe0c451bbbd62dc8ec9cc22d33e1e1ac812538d3bb4aea3f7906d5bR84