C# 直接创建对象和浅表复制哪个性能更加高

2022年3月29日 2052点热度 1人点赞 1条评论
内容目录
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;

public unsafe class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    private static Model _model = new Model();
    public static Model Clone()
    {
        var model = (Model)_model.MemberwiseClone();
        return model;
    }
}

[SimpleJob(RuntimeMoniker.Net60)]
[RPlotExporter]
public class InstanceObject
{
    [Benchmark]
    public void Create()
    {
        Model model = new Model();
    }

    [Benchmark]
    public void Clone()
    {
        var model = Model.Clone();
    }
}

public class Program
{
    public static void Main()
    {
        var summary = BenchmarkRunner.Run<InstanceObject>();
        Console.ReadKey();
    }
}

file


public unsafe class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public int* _id { get; private set; }

    public Model()
    {
        var id = stackalloc int[1000];
        _id = id;
    }

    private static Model _model = new Model();
    public static Model Clone()
    {
        var model = (Model)_model.MemberwiseClone();
        return model;
    }
}

file

public struct A
{
    public long A1;
    public long A2;
    public long A3;
    public long A4;
    public long A5;
    public long A6;
    public long A7;
    public long A8;
}

public struct B
{
    public A A1;
    public A A2;
    public A A3;
    public A A4;
    public A A5;
    public A A6;
    public A A7;
    public A A8;
}

public class Model
{

    public B B1;
    public B B2;
    public B B3;
    public B B4;
    public B B5;
    public B B6;
    public B B7;
    public B B8;

    private static Model _model = new Model();
    public static Model Clone()
    {
        var model = (Model)_model.MemberwiseClone();
        return model;
    }
}

file

结论:无论如何都是 new 直接创建对象快。

痴者工良

高级程序员劝退师

文章评论

  • yuan来是你

    hi,工良

    2022年5月31日