matter-js icon indicating copy to clipboard operation
matter-js copied to clipboard

Rethinking of Math.min/max functions (perfomance suggest)

Open TheLucifurry opened this issue 3 years ago • 3 comments

Hi)

This benchmark shows, that native Math functions might be less perfomant than custom realisations on ternary operator

I suggest to replace all the usings Math.min & Math.max functions to custom realisations I can do it itself, but i don't know, how you testing the pefomance of engine

Are there any reasons why we shouldn't do this?

TheLucifurry avatar Jun 17 '21 09:06 TheLucifurry

I tried it out and the very first test showed all ternary variants to be fastest: image

However, on later runs Math variants catched up but were still behind. I assume this has to do with some sort of optimization from running the tests multiple times.

Anyways, my best guess to why Math is slow because you can pass more than 2 numbers to min/max and have the highest/lowest returned respectively. The implementation probably has extra overhead because of that.

Just giving my thoughts...

AurangAsif avatar Jun 17 '21 15:06 AurangAsif

Yes, most likely Math functions are slower due to the dynamic number of parameters However, after examining the source code of Matter.js, I did not find cases of passing more than 2 parameters in Math functions

Also, I updated the benchmark by adding "ternary inline" variants The funny thing is that the "inlined" option is slower than the option in the function)) бенч

TheLucifurry avatar Jun 18 '21 01:06 TheLucifurry

Thanks for reporting, I can confirm it helps as I've been working on a pure performance branch that includes this, plus a bunch of other things :) I'm working on wrapping it up, so will post back here when it's ready.

liabru avatar Jun 26 '21 19:06 liabru

The performance branch changes were merged a while back as part of 0.18.0 after a lot of benchmarking. At the time, surprisingly Math.min appeared better in some very specific parts of the resolver loops, so I think it will remain for now until revisited.

liabru avatar Mar 16 '23 00:03 liabru