2

I have a basic question that I was hoping someone could answer please.

In PHP, is it quicker to refer back to properties of an object over and over again, or is it faster to copy those properties into an array, if they're being used so much?

This is if you have an object already instantiated and populated fully. When you want to constantly pass some of that objects properties into various functions, should I just reuse the object, or is that in some way creating an overhead that it wouldn't in an array?

Example: I have a Request object. This object has several search parameters. I want to keep on referring to these different search parameters, so currently I'm using:

$request->d->postcode

Someone suggested copying these search parameters into an array first, then re-using the array instead:

$searchParams = get_object_vars($request->d);

then I can simply use:

$searchParams['postcode']

Many thanks for any advice.

3
  • On the contrary: in modern versions of PHP, objects can have better performance than arrays. Why don't you try it? (In fact, it will probably make little difference to you.) Commented Nov 13, 2013 at 9:45
  • 2
    Benchmark it both ways. Iff you see any noticeable difference, decide whether the changed code is worth the tiny difference in performance. Commented Nov 13, 2013 at 9:46
  • If you use the search params to query a database, this will cost much more cpu cycles than anything that you do with the variables in php. Commented Nov 13, 2013 at 9:57

1 Answer 1

2

I think this is a matter of personal preference.

One of the great things about objects is they reduce multiplication in your code, putting the object into an array creates unnecessary duplication and can make your code overly complex (the same values in differently named variables).

I find it easier to keep all data in my code in the same object(s). This makes it more readable for others as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.