I wonder what is the fastest way to do shallow copying in C#? I only know there are 2 ways to do shallow copy:
In fact, MemberwiseClone is usually much better than others, especially for complex type.
The reason is that:if you manual create a copy, it must call one of the type's constructor, but use memberwise clone, I guess it just copy a block of memory. for those types has very expensive construct actions, memberwise clone is absolutely the best way.
Onece i wrote such type: {string A = Guid.NewGuid().ToString()}, I found memberwise clone is muct faster than create a new instance and manual assign members.
The code below's result:
Manual Copy:00:00:00.0017099
MemberwiseClone:00:00:00.0009911
namespace MoeCard.TestConsole
{
class Program
{
static void Main(string[] args)
{
Program p = new Program() { AAA = Guid.NewGuid().ToString(), BBB = 123 };
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
{
p.Copy1();
}
sw.Stop();
Console.WriteLine("Manual Copy:" + sw.Elapsed);
sw.Restart();
for (int i = 0; i < 10000; i++)
{
p.Copy2();
}
sw.Stop();
Console.WriteLine("MemberwiseClone:" + sw.Elapsed);
Console.ReadLine();
}
public string AAA;
public int BBB;
public Class1 CCC = new Class1();
public Program Copy1()
{
return new Program() { AAA = AAA, BBB = BBB, CCC = CCC };
}
public Program Copy2()
{
return this.MemberwiseClone() as Program;
}
public class Class1
{
public DateTime Date = DateTime.Now;
}
}
}
finally, I provide my code here:
#region 数据克隆
///
/// 依据不同类型所存储的克隆句柄集合
///
private static readonly Dictionary> CloneHandlers = new Dictionary>();
///
/// 根据指定的实例,克隆一份新的实例
///
/// 待克隆的实例
/// 被克隆的新的实例
public static object CloneInstance(object source)
{
if (source == null)
{
return null;
}
Func