mikebronner / laravel-model-caching

Eloquent model-caching made easy.
MIT License
2.24k stars 213 forks source link

Reduce memory footprint #351

Closed saernz closed 4 years ago

saernz commented 4 years ago

Hiya, I've been doing a bit of memory profiling recently to solve an issue, whereas I don't think this is my issue I think it could help reduce this libraries memory consumption through a very minor change.

At the line below: https://github.com/GeneaLabs/laravel-model-caching/blob/7e7f527b0e845ab410c78324de5af7e31f61f993/src/Traits/Buildable.php#L223

the debug_backtrace() function is used with default null parameters, if you used debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function']; instead it would drop memory consumption considerably as it won't be loading the entire stack trace each time it is called, which in my case is several thousand times. Including the DEBUG_BACKTRACE_IGNORE_ARGS would also help further to drop the amount of memory used as it wont include function arguments in the returned objects which it doesn't look like is needed anyway.

A function similar to yours but with these optimisations exists in Illuminate and it seems they still have access to the function field. https://github.com/illuminate/database/blob/73d1eb0b9933726977d2a1422454d9e4161b3971/Eloquent/Concerns/HasRelationships.php#L310

Hope this helps :)

mikebronner commented 4 years ago

@saernz Thank you!!!! That is awesome.

mikebronner commented 4 years ago

@saernz Can you check release 0.8.6 and let me know if that improved things?

saernz commented 4 years ago

Oh wow you're fast! Unfortunately I'm not on the new version yet, though I have made the same changes on the older version locally and there is definitely a difference.

This is before the change: Screen Shot 2020-05-13 at 3 06 32 PM

and this is after: Screen Shot 2020-05-13 at 4 50 02 PM

The debug_backtrace function has shrunk away and is no longer filling the graph. It looks like it has gone from 23.28% relative cost to 0.64%.

I'm not sure how it will help the library as a whole but it should improve that function I hope.

mikebronner commented 4 years ago

@saernz What profiler are you using? I've used some clunky ones ones in the past and haven't been happy with them.

saernz commented 4 years ago

@mikebronner This one is called qcachegrind, previously I was using webgrind because I'm on a Mac but that doesn't show memory unfortunately. Luckily I found homebrew has a formula for qcachegrind which makes it really easy to install.