I have some images stored in a database as base64 strings and need to return them from an MVC controller. How can I do that without a memory leak?
Previously I was using this:
return File(Convert.FromBase64String(pictureString), "image/jpeg");
However, the w3wp process starts using up a whole heap of memory for a few photos.
Is there a proper way to do this? Currently I’ve decided just to set each image to data:image/jpg;base64,string_here and it uses a lot less memory.. but it seems to be a lot slower loading the page too.
Any help is appreciated.
+1 To Darin Dimitrov’s comment.
If images / base64 encoded data are more than 85K it will be allocated on LOH (lage objects heap). GC for such allocations is more expensive due to need to wait for generation 2 collection.
Another approach if you have to keep using base64 encoded images is to implement your own stream that reads data from the Base64 encoded value in chunks to avoid allocation of second large block of memory. If you can read string in chunck also you will be able to avoid allocation of objects on LOH and potentially just reuse realitely small buffers to read/decode.