C# – Why is using ComponentResourceManager to set an image around 100ms slower than using Bitmap

coptimizationperformancestartupwinforms

I am using Winforms and need my program's startup to be as fast as possible. Every millisecond counts.

I found an interesting observation. When adding an image using a resource (Winform's default way of adding an image to a control) to say, a button, it takes about 100 milliseconds longer for the form to load compared to when I add a straight bitmap. Compare:

System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image")));

The below code is around 100ms faster (speed gain doesn't apply for additional images though):

button1.Image = new Bitmap("myimage.png");

I was wondering why the former is so slow, and if I can somehow speed it up? I'd rather use the former because it embeds the picture inside the exe (and I don't want to supply all the images separately).

The issue applies with probably all controls which allow an image to be added (I tested with a picture box and a button).

Best Answer

try to preConstruct System.ComponentModel.ComponentResourceManager resources. probably that extra 100ms is for construction of ComponentResourceManager object