Increase Performance By Optimizing Output Filters In MODX

Why do I need to optimize Output Filters?

Let's face it, we use output filters because they are easy. It's much more convenient to quickly add an :is= and a :then= than to build a whole new chunk or snippet. But where does that lead? A few months down the line you may realize those chains of output filters are piling seconds onto your response times.

What is it actually hurting?

Output filters increase parsing, especially if they are used haphazardly. Code left exposed between the ticks can still be processed even if it isn't being displayed on the resulting page.

Example A

Uncached Results
Parse time 0.0268710 s
Queries 7
Queries time 0.0037 s
Cached Results
Parse time 0.0213151 s
Queries 5
Queries time 0.0017419 s

Example B

Uncached Results
Parse time 0.0003791 s
Queries 0
Queries time 0 s
Cached Results
Parse time 0.0002580 s
Queries 0
Queries time 0 s

In both examples above, the formula evaluates to false. In Example A, the pdoMenu call is still parsed as a tag, just not shown.  In example B the parsing by placing the brackets on the outside of the call. Additionally, in B we've reduced error logging and an additional unnecessary query by adding an :else=`-` which prevents MODX from trying to parse the tags.

Now let's try a third example, where we replace Output Filters altogether with a Snippet.

Example C

ShowMenu Snippet:

if(in_array($modx->resource->template, array(1,2))){
    return $modx->runSnippet('Wayfinder',array('startId'=>'0'));
Uncached Results
Parse time 0.0071211 s
Queries 1
Queries time 0.0003810 s
Cached Results
Parse time 0.0065520 s
Queries 0
Queries time 0 s

Of the three examples, B creates the best overall performance when the result is false. This is because MODX is just parsing text, and not executing queries or searching for snippets or chunks. This is a great option if you can get your output filter down to a concise text injection.

When I am optimizing sites, I look for a combination of B and C to balance out queries and parse times while maintaining ease of managing the site. After all, too many one-off Snippets can be a nightmare to navigate. However, it makes much more sense to write a dedicated Snippet to handle complex dynamic output while keeping it all referenced in a common Template or Chunk.

If you are wondering if Output Filters are having a negative effect on your site's performance, I highly recommend giving debugParser a try. It creates a waterfall chart of parse times on a Resource and can expose some nasty issues you weren't aware of. It is my go-to tool for identifying slow scripts and improving site performance.