hotwired-laravel / turbo-laravel

This package gives you a set of conventions to make the most out of Hotwire in Laravel.
https://turbo-laravel.com
MIT License
793 stars 48 forks source link

Reuse `Name` instances to improve performance #106

Closed tobyzerner closed 1 year ago

tobyzerner commented 1 year ago

I have a project with a lot of components and dom_id or dom_class being called hundreds of times on each page load.

This PR optimizes the performance of these functions by reusing Name instances such that the name for a particular class only ever has to be calculated once.

The calculation (in the Tonysm\TurboLaravel\Models\Naming\Name::build method) is actually somewhat expensive when done in large quantities – mostly as a result of the use of the config helper in removeRootNamespaces (resolving from the container each time adds up), and the call to Str::plural.

Ideally the public properties of the Name class would be made readonly so these instances are immutable, however would require dropping PHP 8.0 support.

tonysm commented 1 year ago

@tobyzerner you gave me a reason to test out the PHPBench tool and here's the result:

./vendor/bin/phpbench run --report=default
PHPBench (1.2.10) running benchmarks... #standwithukraine
with configuration file: /Users/tonymessias/Code/turbo-laravel/phpbench.json
with PHP version 8.2.1, xdebug ❌, opcache ❌

\ModelNamesBench

    benchWithoutCachingClassNames...........I0 - Mo3.596μs (±0.00%)
    benchWithCachingClassNames..............I0 - Mo0.252μs (±0.00%)

Subjects: 2, Assertions: 0, Failures: 0, Errors: 0
+------+-----------------+-------------------------------+-----+-------+------------+----------+--------------+----------------+
| iter | benchmark       | subject                       | set | revs  | mem_peak   | time_avg | comp_z_value | comp_deviation |
+------+-----------------+-------------------------------+-----+-------+------------+----------+--------------+----------------+
| 0    | ModelNamesBench | benchWithoutCachingClassNames |     | 10000 | 9,126,832b | 3.596μs  | +0.00σ       | +0.00%         |
| 0    | ModelNamesBench | benchWithCachingClassNames    |     | 10000 | 9,126,848b | 0.252μs  | +0.00σ       | +0.00%         |
+------+-----------------+-------------------------------+-----+-------+------------+----------+--------------+----------------+

It went from 3.596μs to just 0.252μs on 10,000 consecutive runs (revs).

tonysm commented 1 year ago

Tagged as 1.12.1