Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Fixing N+1 With a Join?

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

We made a huge leap forward by telling Doctrine to make COUNT queries to count the comments for each BigFootSighting... instead of querying for all the comments just to count them. That's a big win.

Could we go further... and make a smarter query that can grab all this data at once? That is the classic solution to the N+1 problem: need the data for some Bigfoot sightings and their comments? Add a JOIN and get all the data at once! Let's give that a try!

Adding he JOIN

The controller for this page lives at src/Controller/MainController.php - it's the homepage() method:

... lines 1 - 16
class MainController extends AbstractController
{
/**
* @Route("/", name="app_homepage")
*/
public function homepage(BigFootSightingRepository $bigFootSightingRepository)
{
$sightings = $this->createSightingsPaginator(1, $bigFootSightingRepository);
return $this->render('main/homepage.html.twig', [
'sightings' => $sightings
]);
}
... lines 30 - 120
}

To help make the query, this uses a function in src/Repository/BigFootSightingRepository.php - this findLatestQueryBuilder():

... lines 1 - 15
class BigFootSightingRepository extends ServiceEntityRepository
{
... lines 18 - 22
public function findLatestQueryBuilder(int $maxResults): QueryBuilder
{
return $this->createQueryBuilder('big_foot_sighting')
->setMaxResults($maxResults)
->orderBy('big_foot_sighting.createdAt', 'DESC');
}
... lines 29 - 57
}

This method ... if you did some digging ... creates the query that returns these results.

And... it's fairly simple: it grabs all the records from the big_foot_sighting table, orders them by createdAt and sets a max result - a LIMIT.

To also get the comment data, add leftJoin() on big_foot_sighting.comments and alias that joined table as comments. Then use addSelect('comments') to not only join, but also select all the fields from comment:

... lines 1 - 15
class BigFootSightingRepository extends ServiceEntityRepository
{
... lines 18 - 22
public function findLatestQueryBuilder(int $maxResults): QueryBuilder
{
return $this->createQueryBuilder('big_foot_sighting')
->leftJoin('big_foot_sighting.comments', 'comments')
->addSelect('comments')
->setMaxResults($maxResults)
->orderBy('big_foot_sighting.createdAt', 'DESC');
}
... lines 31 - 59
}

Let's... see what happens! To be safe, clear the cache:

php bin/console cache:clear

And warm it up:

php bin/console cache:warmup

Now, move over, refresh and profile! I'll call this one: [Recording] Homepage with join: https://bit.ly/sf-bf-join.

Go check it out! Woh! This... looks weird... it looks worse! Let's do a compare from the EXTRA_LAZY profile to the new one: https://bit.ly/sf-bf-join-compare.

Wow... this is much, much worse: CPU is way up, I/O... it's up in every category, especially network: the amount of data that went over the network. We did make less queries - victory! - but they took 8 milliseconds longer. We're now returning way more data than before.

So this was a bad change. It seems obvious now - but in a different situation where you might be doing different things with the data, this same solution could have been the right one! Let's remove the join and rely on the EXTRA_LAZY solution.

A Smarter Join?

Yes, this will mean that we will once again have 27 queries. If you don't like that, there is another solution: you could make the JOIN query smarter - it would look like this:

// src/Repository/BigFootSightingRepository.php
public function findLatestQueryBuilder(int $maxResults): QueryBuilder
{
    return $this->createQueryBuilder('big_foot_sighting')
        ->leftJoin('big_foot_sighting.comments', 'comments')
        ->groupBy('big_foot_sighting.id')
        ->addSelect('COUNT(comments.id) as comment_count')
        ->setMaxResults($maxResults)
        ->orderBy('big_foot_sighting.createdAt', 'DESC');
}

The key is that instead of selecting all the comment data... which we don't need... this selects only the count. It gets the exact data we need, in one query. From a performance standpoint, it's probably the perfect solution.

But... it has a downside: complexity. Instead of returning an array of BigFootSighting objects, this will return an array of... arrays... where each has a 0 key that is the BigFootSighting object and a comment_count key with the count. It's just... a bit weird to deal with. For example, the template would need to be updated to take this into account:

{% for sightingData in sightings %}
    {% set sighting = sightingData.0 %}
    {% set commentCount = sightingData.comment_count %}

    {# ... #}
        {{ sighting.title }}

        {{ commentCount }}
    {# ... #}
{% endfor %}

And... because of the pagination that this app is using... the new query would actually produce an error. So let's keep things how they are now. If the extra queries ever become a real problem on production, then we can think about spending time improving this. Sometimes profiling is about knowing what not to fix... because it may not be worth it.

Next, if you were surprised that we didn't see any evidence of the network request that the homepage is making to render the SymfonyCasts repository info from GitHub, that's because the homepage is more complex than it might seem. Let's use a cool "Profile all" feature to see all requests that the homepage makes.

Leave a comment!

0
Login or Register to join the conversation
Cat in space

"Houston: no signs of life"
Start the conversation!

This tutorial can be used to learn how to profile any app - including Symfony 5.

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "blackfire/php-sdk": "^1.20", // v1.20.0
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "doctrine/annotations": "^1.0", // v1.8.0
        "doctrine/doctrine-bundle": "^1.6.10|^2.0", // 1.11.2
        "doctrine/doctrine-migrations-bundle": "^1.3|^2.0", // v2.0.0
        "doctrine/orm": "^2.5.11", // v2.6.4
        "phpdocumentor/reflection-docblock": "^3.0|^4.0", // 4.3.2
        "sensio/framework-extra-bundle": "^5.4", // v5.5.1
        "symfony/console": "4.3.*", // v4.3.10
        "symfony/dotenv": "4.3.*", // v4.3.10
        "symfony/flex": "^1.9", // v1.18.7
        "symfony/form": "4.3.*", // v4.3.10
        "symfony/framework-bundle": "4.3.*", // v4.3.9
        "symfony/http-client": "4.3.*", // v4.3.10
        "symfony/property-access": "4.3.*", // v4.3.10
        "symfony/property-info": "4.3.*", // v4.3.10
        "symfony/security-bundle": "4.3.*", // v4.3.10
        "symfony/serializer": "4.3.*", // v4.3.10
        "symfony/twig-bundle": "4.3.*", // v4.3.10
        "symfony/validator": "4.3.*", // v4.3.10
        "symfony/webpack-encore-bundle": "^1.6", // v1.7.2
        "symfony/yaml": "4.3.*", // v4.3.10
        "twig/extensions": "^1.5" // v1.5.4
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.2", // 3.2.2
        "easycorp/easy-log-handler": "^1.0.7", // v1.0.9
        "fzaninotto/faker": "^1.8", // v1.8.0
        "symfony/browser-kit": "4.3.*", // v4.3.10
        "symfony/css-selector": "4.3.*", // v4.3.10
        "symfony/debug-bundle": "4.3.*", // v4.3.10
        "symfony/maker-bundle": "^1.13", // v1.14.3
        "symfony/monolog-bundle": "^3.0", // v3.5.0
        "symfony/phpunit-bridge": "^5.0", // v5.0.3
        "symfony/stopwatch": "4.3.*", // v4.3.10
        "symfony/var-dumper": "4.3.*", // v4.3.10
        "symfony/web-profiler-bundle": "4.3.*" // v4.3.10
    }
}
userVoice