Cloning objects in C #

Consider this related question: Deep cloning objects

Is this really the best way to clone an object? (Serialization / Deserialization). Serialization seems expensive to me.

My idea was to create a second constructor and just assign all the variables. Will this approach be faster?

class Test
{

public Test(Test clone)
{
// clone ....
}
}

      

+3


source to share


6 answers


If you are talking about using a custom class, the best way is implementation ICloneable

. This way your class can provide a standardized way to clone.



Sometimes using a "copy constructor" can be better, but usually only if you can see that it will be simple and ICloneable

does not adequately meet your needs.

+1


source


It depends on what you want to clone and why. If the shallow clone is ok, then:

private static T CloneShallow<T>(T i) {
    return
        (T)i.GetType()
            .GetMethod(
                "MemberwiseClone",
                BindingFlags.Instance | BindingFlags.NonPublic
            ).Invoke(i, null);
}

      

This is the fastest way to clone any type of simple post.

If you want a full copy, but it's not time critical, then:

private static T CloneFull<T>(T i) {
    if (Object.ReferenceEquals(i, null)) return default(T);
    var x = new XmlSerializer(i.GetType());
    using (var m = new MemoryStream()) {
        x.Serialize(m, i);
        m.Seek(0, SeekOrigin.Begin);
        return (T)x.Deserialize(m);
    }
}

      



The second is about 70 times slower than the first.

If you want a complete copy and speed is important, consider using protobuf-net as your serializer.

There are many answers out there related to modifying the object you want to clone, but often you just need to clone a simple entry and you don't want to implement anything on it.

And if you're wondering how slow CloneFull () is - on my computer (i5 661 @ 3.33 GHz) with a very simple write, then it took 360 ticks, which gives 36ns. In most cases this is fast enough :)

+6


source


The key phrase is in the accepted answer

The advantage is that you don't have to worry about cloning everything when the object gets too complex.

The serialization method works for any object of any complexity. While this may well be overkill for smaller, simpler objects, it is a scalable solution.

If you know that your object is not going to change and you only want to clone simple objects, your approach is fine. Although the ICloneable implementation is the preferred solution.

+2


source


The question you are linking to is talking about clone generation, which works for anything that supports serialization. If you only want to clone for your specific object, just implement ICloneable

.

class Test : ICloneable {
    public object Clone() {
        // clone ....
    }
}

      

+2


source


Serialization is only , especially useful for storing a representation of an object that you want to retrieve later / elsewhere. There is an ICloneable interface that you must implement if you want the object to be cloned.

+1


source


ICloneable

:

Supports cloning, which creates a new instance of a class with the same value as an existing instance. The ICloneable interface contains a single member, Clone, which is designed to support cloning beyond that provided by MemberwiseClone. For more information on cloning, depths, and shallow copy and examples, see the Object.MemberwiseClone method.

+1


source







All Articles