ebvtrnog
ebvtrnog

Reputation: 4367

Performance of Image loading

I've been experimenting for a few hours with various ways to load an image from file. Please have a look at these two methods:

    public Image SlowLoad(string path)
    {
        return Image.FromFile(path);
    }

    public Image FastLoad(string path)
    {
        using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path)))
            return Image.FromStream(ms);  
    }

The second method is like 2 times faster. What am I missing here? Why is it so? I can't believe that .NET developers couldn't implement Image.FromFile faster simply using the method I wrote. So => I am wrong somewhere. Please tell me where. Why is the second method almost 2 times faster? Is my code fully correct? (thread-safe, etc.). Maybe Image.FromFile is more secure?

Upvotes: 5

Views: 5296

Answers (1)

Ilia Maskov
Ilia Maskov

Reputation: 1898

AFAIK: First of all Image.FromFile wraps GDI+ GdipLoadImageFromFile* functions, ones has a strange life. GDI+ image holds and can use source (file or stream) during whole lifetime, some details about it http://support.microsoft.com/en-us/kb/814675. So, here is some possible "multiple file io" vs "multiple stream io". Also there is some interesting comment in MS Reference Source System.Drawing.Image:

http://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Image.cs,181

class Image {
    ............
    public static Image FromFile(String filename,
                                     bool useEmbeddedColorManagement) 
    {
        ............    
        //GDI+ will read this file multiple times. 
        ............
    }
}

Upvotes: 2

Related Questions