Henrik Petterson
Henrik Petterson

Reputation: 7094

Is it worth to cache foreach loops?

I have 3 separate arrays containing around a list of 20 article titles. I have each array stored in its own key in the database.

To display the article titles, I look through each array via foreach().

My question is, would it be worth it when considering micro-optimisation to cache the loop results? So the difference is that the HTML output of the foreach will be stored in each of the 3 keys in the database.

This means, slightly larger content in the database key, but no need to loop through it later.

Upvotes: 1

Views: 688

Answers (1)

Carmax
Carmax

Reputation: 2917

I do not think it would be worth doing this.

The extra complexity it would add to your code would not be justified by the minimal performance boost (and in all honesty there might not even be one).

Although it might depend on how often the loop results change, and how many times the page is being called, etc....

But ultimately, if you have the article titles already in an array, it requires very little juice to iterate through them.

PS. If you're interested in the theory, I just came across this question: How does PHP 'foreach' actually work?

Upvotes: 2

Related Questions