Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__get/__set/__call performance questions with PHP

I have a custom-built MVC PHP framework that I am in the process of rewriting and had a question about performance and magic methods. With the model portion of the framework, I was thinking if __get/__set magic methods would cause too much performance hit to be worth using. I mean accessing (reads and writes) model data is going to be one of the most common things performed. Is the use of __get/__set magic methods too big of a performance hit for heavy use functionality like the model portion of a MVC framework?

like image 660
ryanzec Avatar asked Jul 25 '10 20:07

ryanzec


2 Answers

Measure it.

It certainly has a big performance hit, especially considering function calls are expensive in PHP. This difference will be even bigger in the next version of PHP, which implements optimizations that render regular access to declared instance properties significantly faster.

That said, PHP rarely is the bottleneck. I/O and database queries frequently take much more time. This, however, depends on your usage; the only way to know for sure it to benchmark.

That are also other readability problems with the magic methods. They frequently degenerate into one big switch statement and compromise code completion, both of which may be hits in programming productivity.

like image 194
Artefacto Avatar answered Sep 24 '22 23:09

Artefacto


Here's a an article (three years old) with some benchmarks. Run your own tests to see how it impacts your code.

Generally speaking, they are much slower. But are they the bottleneck? It depends what you are doing. If you're concerned about speed, where does it stop? The foreach loop is slower than the for loop, yet most people don't rewrite all of their code to use the for.

Just using PHP means that the speed of your code isn't all that critical. Personally, I would favor whatever style makes it easier to program.

like image 29
Matthew Avatar answered Sep 23 '22 23:09

Matthew