面向云技术架构 - 痴者工良

  • 首页
  • 工良写的电子书
    • kubernetes 教程
    • 从 C# 入门 Kafka
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 本站文章导航
  • 隐私政策
愿有人陪你颠沛流离
遇到能让你付出的事物或者人,都是一种运气。
能遇到,就该珍惜。或许你们最终没能在一起,但你会切实地感受到力量。
正因为这样,那段相遇才变得有价值,才没有辜负这世间的每一段相遇。
  1. 首页
  2. 笔记和吹水
  3. 代码片段
  4. 正文

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

2022年3月29日 686点热度 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 直接创建对象快。

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: c 创建对象 哪个 复制 浅表
最后更新:2022年3月29日

痴者工良

高级程序员劝退师

点赞
< 上一篇
下一篇 >

文章评论

  • yuan来是你

    hi,工良

    2022年5月31日
    回复
  • razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
    取消回复

    COPYRIGHT © 2022 whuanle.cn. ALL RIGHTS RESERVED.

    Theme Kratos Made By Seaton Jiang

    粤ICP备18051778号

    粤公网安备 44030902003257号