Untitled

 avatar
unknown
csharp
a year ago
1.7 kB
3
Indexable
using System;
using System.Linq.Expressions;
using BenchmarkDotNet.Attributes;

namespace ConsoleApp1;

public class ObjectCreationBenchmark
{
    public class FooClass
    {
        public int A { get; set; }

        public Guid B { get; set; }
    }

    public record struct FooStruct
    {
        public int A { get; set; }

        public Guid B { get; set; }
    }

    [Benchmark]
    public FooClass ActivatorCreateInstance_RefType()
    {
        return Activator.CreateInstance<FooClass>();
    }

    [Benchmark]
    public FooClass FastCreate_RefType()
    {
        return FastObjectCreationHelper<FooClass>.Create();
    }

    [Benchmark]
    public FooStruct ActivatorCreateInstance_ValueStructType()
    {
        return Activator.CreateInstance<FooStruct>();
    }

    [Benchmark]
    public FooStruct FastCreate_ValueStructType()
    {
        return FastObjectCreationHelper<FooStruct>.Create();
    }

    [Benchmark]
    public long ActivatorCreateInstance_ValueLongType()
    {
        return Activator.CreateInstance<long>();
    }

    [Benchmark]
    public long FastCreate_ValueLongType()
    {
        return FastObjectCreationHelper<long>.Create();
    }

    private static class ConstraintsHelper
    {
        public static T Create<T>() where T : new()
        {
            return new T();
        }
    }

    private static class FastObjectCreationHelper<T>
    {
        private static readonly Func<T> X = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();
        public static T Create()
        {
            return X();
        }
    }
}
Editor is loading...
Leave a Comment