Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC slow image loading through MVC framework?

On some photobook page i want to show appr 20 thumbnails. These thumbnails are programatically loaded from a database. those thumbnails are already resized. When i show them the images load kinda slow. some take 0.5 seconds to load some wait for 2 secons. The database doesn't matter because when i remove the database layer, the performance issue still exists.When i load the same images directly with html the problem the images do load immediately.

Is loading images/files through the mvc framework slow or am i missing something?

This goes too slow

//in html
<img src='/File/Image.jpg' border='0'>                    

//in controller
public FileResult File(string ID)
{           
    //database connection removed, just show a pic
    byte[] imageFile = System.IO.File.ReadAllBytes(ID);
    return new FileContentResult(imageFile,"image/pjpeg");
}

This goes immediately

<img src='/Content/Images/Image.jpg' border='0'>                    
like image 291
MichaelD Avatar asked Aug 12 '10 19:08

MichaelD


2 Answers

I had the same issue. I'm using MVC 3. After pulling my hair out, what I discovered is that once you use Session State in your web app, dynamic image loading seems to get clogged, due to the pounding session requests. To fix this, I decorated my controller with:

[SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]

This disabled the session state for my Photos controller, and the speed returned. If you are using an earlier version of MVC, you'll need to jump through some hoops and create a Controller/Controller factory to do this. See How can I disable session state in ASP.NET MVC?

Hope this helps!

like image 171
Myke Maas Avatar answered Oct 19 '22 23:10

Myke Maas


You are adding processing overhead by exposing the image via MVC. When you directly link to an image, it is handled automatically by IIS, rather than the MVC pipeline, so you skip a lot of overhead.

Also, by loading into a byte array, you're loading the full image from disk into memory and then streaming it out, rather than just streaming directly from disk.

You might get slightly better performance with this:

[OutputCache(Duration=60, VaryByParam="*")]
public FileResult File(string ID)
{   
    string pathToFile;
    // Figure out file path based on ID
    return File(pathToFile, "image/jpeg");
}

But it's not going to be quite as fast as skipping MVC altogether for static files.

If the above fixes it for you, you'll probably want to mess around with the caching parameters.

like image 36
Bennor McCarthy Avatar answered Oct 19 '22 23:10

Bennor McCarthy