4 ms·
> Avoid writing naive setters and getters You might as well avoid double-quote strings while you are at it. The test had 1 000 000 iterations which means that
by voidr 15y ago
> Avoid writing naive setters and getters
You might as well avoid double-quote strings while you are at it.
The test had 1 000 000 iterations which means that you won't gain more than a few micro/miliseconds by doing this.
I would call this advice: naive optimization.
- stephenr 15y agoEven more troubling to me, is that the author completely ignorss magic methods __get and __set. I ran the two tests he provided locally, as well as an altered version to use __get and __set, and the direct access method, and using magic methods were both roughly 10x the speed of the getName, setName methods. Even ignoring the performance issue, why would you even consider using an explicit setName over __set ?
- wvenable 15y ago> and using magic methods were both roughly 10x the speed of the getName, setName methods. That seems counter-intuitive -- in both cases, methods are being called (which is slow in PHP), so why would __get and __set be faster?
- voidr 15y agoForgot about those. Also I didn't know that they were actually faster. In very simple classes I think the explicit getters and setters get the job done. Of course if you want to invoke it a lot your solution is a lot better. I was mainly debating the notion of sacrificing readability and maintainability for the sake of a few microseconds, I feel it's wrong, if you care about speed that much, I think you shouldn't be using PHP in the first place.
- pornel 15y ago> why would you even consider using an explicit setName over __set ? • You don't put logic of all setters in one place. Although you could create some dispatcher in __set that looks up method for the setter and calls it, that's a bit of magic that may not be expected by someone using the class. • You can control visibility and override setters using standard PHP syntax rather than custom code in __set() • Inside the class and derived classes it's clear when `$this->foo` is direct access and when it's a setter, otherwise you need to be careful about property declarations and visibility. • It's possible to pass extra optional arguments to the setter (none of these points are particularly strong, but there are non-insane reasons to use setters)