I have a function in Symfony2 that modifies an object. The function can receive the object in one of two ways. First, the object can be passed to the function like this:
public function myFunction(Object $myObject)
{
// Do something with $myObject
}
Alternately, an object id (or any other attribute) can be passed to the function and used to find the object within the function, like this:
public function myFunction($id)
{
$myObject = $this->entityManager->getRepository('AppBundle\Entity\Object')->find($id);
// Do something with $myObject
}
Functionally, these two methods are equivalent. My question is, how do these two methods differ in their effect on the application's performance? I know the number of database queries should be minimized for optimized performance. So, how does the performance cost of an additional find()
query compare with the performance cost of passing an object to a function?
Passing the object to the function will always be more performant. Since PHP5 objects are passed by object identifier, very similar in concept to pass by reference.
That said, retrieving a single record of raw data from the database is relatively fast. In my experience, hydration (transforming the relational data retrieved from the database into it's mapped business object) is where you find bottlenecks. Marco Pivetta, lead developer of Doctrine, has written an excellent post about this.
Generally speaking, under normal circumstances you will probably notice no difference in performance between passing an object and hydrating a single object. Hydrating in loops, however, is where you run into trouble. The more complex the object, and the more data you hydrate, the worse the performance.