Patrick
Patrick

Reputation: 3367

Using objects for passing information - php

Since PHP objects are passed by reference(reference to the object itself, not to be confused with reference to the variable), does passing a very large object to a function add any resource stress to the system?

This seems like a 'get out of jail free card' for passing information, Since no copies are being made, I can pass a huge object around, while if I pass an array I take a memory hit.

In my OOP coding style, I prefer passing entire objects as arguments instead of just a single attribute, as it makes the code more readable and allows for greater functionality down the road if it's needed.

So my questions :

  1. Am I correct in my assumption that objects infer no resource hit when passed to functions?
  2. Does this scale? Is passing a 1MB object any different than passing a 10MB object?
  3. Is accessing an object attribute the same as accessing an array key? Is there a performance issue involved?

Thanks in advance!

Upvotes: 0

Views: 61

Answers (1)

Niels Keurentjes
Niels Keurentjes

Reputation: 41968

  1. Yes, passing by reference implies no resource hits.
  2. Yes, passing by reference makes no difference between 10 bytes and 10 megabytes.
  3. Yes, internally objects are actually just syntactically refined arrays. PHP is kinda stupid internally.

Bonus answer:

  1. Arrays are also passed by reference, but use a lazy-copy mechanism - they are not actually copied until modified. There is therefore no reason to prefer one over the other, they just fit different needs. In general, passing a 100MB array around to modify minor parts of it is never a good idea and just a consequence of bad decisions elsewhere. Also, if you really need to do this you can (and should) always pass by reference explicitly to eliminate that issue.

As for this line:

In my OOP coding style, I prefer passing entire objects as arguments instead of just a single attribute, as it makes the code more readable and allows for greater functionality down the road if it's needed.

I'm curious about what you mean with that. It sounds a lot like you're sacrificing OOP principles to cover up for architectural mistakes. As a rule of thumb, any interface to any object should pass the least possible information around. Just passing entire objects or arrays around 'for convenience' sounds like very bad architecture or coding style.

Upvotes: 1

Related Questions