__get/__set/__call performance questions with PHP

后端 未结 4 838
时光取名叫无心
时光取名叫无心 2020-12-06 19:23

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 framewor

相关标签:
4条回答
  • 2020-12-06 20:06

    Purely from my experience, it does add a quite a lot over overhead. On a page with about 4000 __get's (yes, there was quite a lot of data on that page) performance was quite measurably slower, to the point it became unacceptable. I threw away all __set's & __get's for variables which wouldn't require other data to be altered or external dependancies (like foreign keys) to be checked, after which the time to generate that page was about 15% of the time it took before.

    0 讨论(0)
  • 2020-12-06 20:06

    I have just asked myself this same question and came to the same conclusion: It's better to set the properties in the traditional way. __get() + massive switch slows everything down

    0 讨论(0)
  • 2020-12-06 20:08

    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.

    0 讨论(0)
  • 2020-12-06 20:12

    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.

    0 讨论(0)
提交回复
热议问题