pmmp / Math

PHP library containing math related code used in PocketMine-MP
GNU Lesser General Public License v3.0
41 stars 22 forks source link

Optimize allocations with thisrc #13

Open SOF3 opened 4 years ago

SOF3 commented 4 years ago

This pull request optimizes unique-reference calls to Vector3, which minimizes object allocations for long call chains like this:

$vector
  ->add(1, 2, 3)
  ->multiply(3)
  ->cross($otherVector)
  ->divide(4)

For the above code, the current implementation requires 4 allocations, while with this patch only one allocation is required.

Adaptability

This patch is not effective when the vector is referenced by any variables, including $this. This means not even calling $this->xxx() from a subclass of Vector3 would utilize this optimization, nor $foo->xxx() (even if $foo is no longer used).

This patch is not effective in some chain calls. For example, this does not optimize anything in $event->getPlayer()->add().

Drawbacks

This requires users to install ext-thisrc. A polyfill or cpp-based alternative may be used to support non-thisrc users.

This involves extra function call overhead in the thisrc() calls. ext-thisrc may be implemented at a lower level of PHP internals (rather than just as a PHP_FUNCTION) may be useful, but that would be much more challenging.

Tasks