Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: detector body sorting #1329

Open
cha0s opened this issue Jan 11, 2025 · 0 comments
Open

Performance: detector body sorting #1329

cha0s opened this issue Jan 11, 2025 · 0 comments

Comments

@cha0s
Copy link

cha0s commented Jan 11, 2025

bodies.sort(Detector._compareBoundsX);

The above code is largely inefficient most of the time in practice. This is because quicksort is generally less efficient on mostly-sorted arrays.

Funny as it may sound, the humble insertion sort is a great candidate for sorting mostly-sorted arrays. This is the case a lot of the time in practice: most objects do not move so far every frame as to essentially randomize the bounds sorting.

Replacing the code above with

  for (let i = 1; i < bodies.length; i++) {
    let current = bodies[i];
    let j = i - 1;
    while ((j > -1) && (current.bounds.min.x < bodies[j].bounds.min.x)) {
      bodies[j + 1] = bodies[j];
      j--;
    }
    bodies[j + 1] = current;
  }

runs almost 25% faster.

You may not agree with this and I'm curious what your opinion is.

Regardless of whether you think this sorting strategy makes sense in a general case, I suggest that the original line of code above is moved to a new method on Detector: sortBodies. If this was done, it would be much easier to swap out a sort that makes sense for your simulation by simply overriding Detector.sortBodies. As it stands today, the entire Detector.collisions method most be overridden to change the sorting strategy for bodies.

Thanks for your work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant