Which is better for performance, where or forloop?

For example, which of the following would be better?

{%- for post in site.posts -%}
	{%- if post.customterm == 'randomkeywords' -%}
  		some codes
	{%- endif -%}
{%- endfor -%}
{%- for post in site.posts | where:"customterm ", "randomkeywords" -%}
  	some codes
{%- endfor -%}

You can’t use filters in the for tag. So you have to assign beforehand:

{% assign foo = site.posts | where: "customterm", "randomkeywords" %}
{% for post in foo %}
  some code
{% endfor %}

Performance-wise, the better route will always be the one that involves less work.
To determine scientifically, you either profile the two scenarios or benchmark them.

1 Like