XF 2.0 Find or finder, is one more efficient over the other?

LPH

Well-known member
Is one statement more efficient than the other? Is one preferable over the other? Are they equivalent in what is returned?

PHP:
 $user = $this->app()->finder('XF:User')->whereId($userId)->fetchOne();

versus

PHP:
 $user = $this->app()->find('XF:User', $userId);
 
They're essentially the same thing, though there's a small optimisation with the latter one. Aside from being quicker to write:
PHP:
$className = $this->getEntityClassName($shortName);
$lookup = $this->getEntityCacheLookupString((array)$id);
if (isset($this->entities[$className][$lookup]))
{
   return $this->entities[$className][$lookup];
}
It is capable of searching the entity cache first, and if the entity has already been fetched then it will come from the cache rather than querying for it again.

You can test this with this code (just pop it into a controller somewhere and check the query count in the debug output:

PHP:
$i = 0;

do
{
   $i++;
   $this->em()->find('XF:User', 1);
}
while ($i < 100);

Query count: 8.

PHP:
$i = 0;

do
{
   $i++;
   $this->em()->getFinder('XF:User')->whereId(1)->fetchOne();
}
while ($i < 100);

Query count: 108.

(The "8" queries are the queries required to load the page where I put this code.)

So, always use the entity manager find method if you can.
 
Back
Top Bottom