Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ortix's avatar

Optimize image loading iteration

I have a laravel application in which the user is presented with a list of episodes, each with a screenshot. Each screenshot is loaded inside a foreach loop in the view as per this pseudo code:

foreach $episodes as $episode
    $episode->getScreenshot($episodeID);
endforeach

The getScreenshot() method resolves a specific ScreenshotLocator class out of the IoC container like so:

$screenshotLocator = App::make('\Animekyun\Images\Screenshots\ScreenshotLocator');

(I'm reading some things about binding it to the container as a singleton. Is that something to consider? Currently it's not bound at all)

The ScreenshotLocator class is designed to build the path to the actual screenshots folder (source below) using the Episode model. The screenshots (there are multiple per episode) are all stored in a folder structure and the necessary files are loaded and stored in a Collection.

The loading of the screenshots takes 40 ms out of the 135 ms for the entire page to load on a Digital Ocean droplet. (10x run benchmark). Note, with loading I mean from Boot to After. Not the actual HTTP requests

So my question is what are some ways to optimize this?

Source for the ScreenshotLocator class: http://laravel.io/bin/6L19r

0 likes
10 replies
RemiC's avatar
RemiC
Best Answer
Level 8

You can use the Cache to retrieve the screenshot from your Episode model.

Ortix's avatar

@RemiC what do you mean? Cache the path to the screenshot on the Episode Model?

Ortix's avatar

So just so we are on the same page: You are suggesting to first check if there is a collection of screenshots cached belonging to a specific episode (retrieval by episode id?) and otherwise go through the entire process of locating the screenshot? Am I correct?

I am assuming I should do this before I resolve the locator out of the IoC container?

Ortix's avatar

Sometimes I wonder why I can't come up with these simple solutions. Thanks, Obama

Ortix's avatar

@RemiC just a note that on my vagrant box I was able to see 31% performance boost using your method. Looks good to me!

1 like
RemiC's avatar

Great!

Which cache driver are you using, File based, Memcached?

Ortix's avatar

Redis, but I will try out memcached later on to see what that does!

EDIT: Memcached seems to be slower

Please or to participate in this conversation.