Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to clone

I am trying to optimize a piece of code that clones an object:

#region ICloneable
public object Clone()
{
    MemoryStream buffer = new MemoryStream();
    BinaryFormatter formatter = new BinaryFormatter();

    formatter.Serialize(buffer, this);     // takes 3.2 seconds
    buffer.Position = 0;
    return formatter.Deserialize(buffer);  // takes 2.1 seconds
}
#endregion

Pretty standard stuff. The problem is that the object is pretty beefy and it takes 5.4 seconds (according ANTS Profiler - I am sure there is the profiler overhead, but still).

Is there a better and faster way to clone?

like image 517
AngryHacker Avatar asked May 06 '10 22:05

AngryHacker


People also ask

What is the fastest way to clone a hard drive?

The fastest and easiest way to clone a hard drive is to use AOMEI Backupper Professional. Its easy-to-use interface and simple operations will save you a lot of time and efforts. You can clone disk to larger disk to get greater capacity or clone hard drive to smaller SSD as you like.

How long does it take to clone HDD to SSD?

People often ask how long does it take to clone a hard drive to SSD. It depends on the size of the data you need to transfer, the speed of the cloning software, the computer device, hard drive, etc. If your cloning speed is 100MB/s, it will take about 17 minutes to clone a 100GB hard drive.

How long does offline cloning take?

So if your cloning speed is 100MB/s, it takes about 17 minutes to clone a 100GB hard drive. If your cloning process takes 87 minutes to clone 500GB data, it is the average speed.


1 Answers

  1. Don't implement ICloneable.

  2. The fast way to clone an object is to create a new instance of the same type and copy/clone all fields from the original instance to the new instance. Don't try to come up with a "generic" clone method that can clone any object of any class.

Example:

class Person
{
    private string firstname;
    private string lastname;
    private int age;

    public Person(string firstname, string lastname, int age)
    {
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }

    public Person Clone()
    {
        return new Person(this.firstname, this.lastname, this.age);
    }
}
like image 92
dtb Avatar answered Sep 29 '22 01:09

dtb