Cloning an object is much faster in performance

Cloning an object in C# is much faster and light weight than creating a new object.

In an IP Camera live video streaming application where one cannot afford a lag in

live video its recommended to clone a bitmap if one want to process captured

bitmap in a separate thread.

Following code demonstrates how cloning is done on a bitmap object to create its clone


Bitmap bmp = new Bitmap("Example.jpg");

Bitmap clonedBmp = (Bitmap)bmp.Clone();

On the other hand creating a new bitmap object from original bitmap is time consuming and requires more memory space because its a deep copy as compared to shallow copy done by cloning an object


Bitmap bmp = new Bitmap("Example.jpg");

Bitmap newBmp = new Bitmap(bmp);

Lets do a comparison

First we are creating a new Bitmap in each loop iteration


Bitmap originalBmp = new Bitmap(@"C:sample.bmp");
long memBefore = Process.GetCurrentProcess().PrivateMemorySize64;
Stopwatch timer = Stopwatch.StartNew();

List<Bitmap> list = new List<Bitmap>();
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
list.Add(new Bitmap(originalBmp));
}

long memAfter = Process.GetCurrentProcess().PrivateMemorySize64;
Debug.WriteLine("Elapsed Milliseconds: " + timer.ElapsedMilliseconds);
Debug.WriteLine("Private MemorySize64: " + (memAfter - memBefore));

Results:

Elapsed Milliseconds:       1987
Private MemorySize64:   262254592

Now Clone object

Bitmap originalBmp = new Bitmap(@"C:sample.bmp");
long memBefore = Process.GetCurrentProcess().PrivateMemorySize64;
Stopwatch timer = Stopwatch.StartNew();

List<Bitmap> list = new List<Bitmap>();
Random rnd = new Random();
for (int i = 0; i < 100; i++)
{
list.Add((Bitmap)originalBmp.Clone());
}

long memAfter = Process.GetCurrentProcess().PrivateMemorySize64;
Debug.WriteLine("Elapsed Milliseconds: " + timer.ElapsedMilliseconds);
Debug.WriteLine("Private MemorySize64: " + (memAfter - memBefore));

Results:

Elapsed Milliseconds:        4
Private MemorySize64:   724992

Difference:

Difference is huge 4 vs 1987 milliseconds

Get Free Email Updates!

Signup now and receive free offers, discounts & coupon codes

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge