3
\$\begingroup\$

My colleague did some code Optimise work.

Code below is from a public method of a public class (NOT STATIC CLASS OR METHOD)

code before:

                Bitmap btMap = new Bitmap(Convert.ToInt32(WebConfig.StatsOpenEmailImageWidth), Convert.ToInt32(WebConfig.StatsOpenEmailImageHeight), PixelFormat.Format32bppArgb);
                MemoryStream memStrm = new MemoryStream();

                btMap.Save(memStrm, ImageFormat.Png);
                memStrm.WriteTo(context.Response.OutputStream);

Code after:

                using (Bitmap btMap = new Bitmap(Convert.ToInt32(WebConfig.StatsOpenEmailImageWidth), Convert.ToInt32(WebConfig.StatsOpenEmailImageHeight), PixelFormat.Format32bppArgb))
                {
                    using (MemoryStream memStrm = new MemoryStream())
                    {
                        btMap.Save(memStrm, ImageFormat.Png);
                        memStrm.WriteTo(context.Response.OutputStream);
                    }
                }

Is it a necessary optimisation againt memory leak?

\$\endgroup\$
2
\$\begingroup\$

Absolutely, the 2nd example is the way to ensure disposable objects/resources are released for the GC. The using clause does this by enforcing the rule that the object being created must inherit from IDisposable. At the closing '}' of each using block, the object is disposed.

In the first example, you will have memory leaks occur if you don't close and dispose the MemoryStream.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.