I use the following method to convert an image to a base64 string:
FileStream fs = new FileStream(imagePath, FileMode.Open,FileAccess.Read);
byte[] filebytes = new byte[fs.Length];
fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
return Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
This method is run at runtime several times for each page load. I am concerned of the impact on performance on my sit开发者_Python百科e.
I am aware it will impact on performance but will it significantly impact on it?
In general the best way to determine performance impact is to measure it. It looks like this might cause some CPU usage, memory overhead, and some disk IO, so those are the areas that I'd watch for trouble. Use a load testing tool to simulate a realistic number of concurrent users, and see what happens.
For what it is worth, if those images are always the same ones, then you can probably cache the output of this method.
I think you'll lose more performance in the garbage collection. IDisposable is our friend.
byte[] filebytes;
using(FileStream fs = new FileStream(imagePath, FileMode.Open,FileAccess.Read))
{
byte[] filebytes = new byte[fs.Length];
fs.Read(filebytes, 0, (int)fs.Length);
}
return Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
The most performance "inefficient" part in your code is reading the images from the file system.
Doing base64 encoding is a very easy algorithm that is done in-memory.
Whether or not this actually impacts the performance of your site depends on the volume of your site and the amount of time reading the files and encoding them compared to everything else your site does. The best thing to do is leave the code as is for now and add some logging to know what the performance impact is.
If you have repeated reads of the same files, you can add a cache to either cache encoded files to memory or encoded files to disk, depending on the size and how often you have repeated file accesses.
精彩评论