3

How does it affect performance by making sure that all my setters return $this? To allow for chain calls similar to jQuery coding standards.

E.g:

public function setEnabled(){
    $_enabled = true;
    return $this;
}

I found this other question with no reference to the performance side, surley there is a negative

Community
  • 1
  • 1
John Magnolia
  • 16,769
  • 36
  • 159
  • 270
  • Would you rather re reference the object for every setMethod? This spares code, who cares it's impact, it has to be better than clogging up the calling script. – Emery King Mar 03 '13 at 18:03
  • Premature optimization is the root of all evil – Eric Mar 03 '13 at 18:12
  • i did some benchmarks on it, returning $this instead of returning void seems to be about 17 nanoseconds slower on my i7-6700 in power-saving mode on battery on a laptop with PHP 7.1.16, benchmark code can be found here: https://github.com/Znote/POTCP/commit/10cd616ffb8257216a8ede8fbe5ce625899536b9 (i would post this as an answer but it's closed..) – hanshenrik Apr 19 '19 at 21:14

5 Answers5

3

No significant performance impact. Objects are not cloned.

Ven
  • 19,015
  • 2
  • 41
  • 61
0

Objects are passed by reference unless you specifically clone them (in php 5 anyway). I don't see any performance impact by doing this.

datasage
  • 19,153
  • 2
  • 48
  • 54
0

NO the another question answer everything, in your code sample your Function will always true, and could be chain if you want

0

PHP return null; is the same as return; which is the same as not returning anything at all. Either way, something is being returned, it may as well be the objects reference to itself.

Emery King
  • 3,550
  • 23
  • 34
  • and yet, in my tests, `return $this;` is about 17 nanoseconds slower than `return;` in php 7.1.16 on i7-6700 - benchmarking code: https://github.com/Znote/POTCP/commit/10cd616ffb8257216a8ede8fbe5ce625899536b9 – hanshenrik Apr 19 '19 at 21:15
0

Most every line of code comes with a performance hit. But is that not the point of writing that line of code

Your question is very vague and depends on a few factors. The size object being returned, how it is being received, and the calculations made on $this before it is being returned.

Usually there is no issues with returning $this but it is all a question of judgement. If $this contains a huge data array, you can figure it will use more memory and processing time than in your example.

Stephane Gosselin
  • 9,030
  • 5
  • 42
  • 65
  • It's just a reference though, not the object itself. It doesn't matter the size until it's used. Which is irrelevant. – Emery King Mar 03 '13 at 18:10