RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.61k stars 1.22k forks source link

use GetValues method instead of GetNames #4828

Closed testfirstcoder closed 3 months ago

testfirstcoder commented 3 months ago

Some performance improvement.

public enum TypeScriptDateTimeType
{
    /// <summary>Uses the JavaScript Date object for date time handling.</summary>
    Date,
    /// <summary>Uses the Moment.js for date time handling.</summary>
    MomentJS,
    /// <summary>Uses the strings for date time handling (no conversion).</summary>
    String,
    /// <summary>Uses the Moment.js for date time with offset handling.</summary>
    OffsetMomentJS,
    /// <summary>Uses Luxon for date time handling.</summary>
    Luxon,
    /// <summary>Uses the DayJS.js for date time handling.</summary>
    DayJS,
}

[SimpleJob(RuntimeMoniker.Net80)]
[MemoryDiagnoser]
public class Benchmark
{
    [Benchmark]
    public void GetNames()
    {
        TypeScriptDateTimeType[] dateTimeTypes = Enum
            .GetNames(typeof(TypeScriptDateTimeType))
            .Select(t => (TypeScriptDateTimeType)Enum.Parse(typeof(TypeScriptDateTimeType), t))
            .ToArray();
    }

    [BenchmarkAttribute]
    public void GetValues_Explicit_Cast()
    {
        TypeScriptDateTimeType[] dateTimeTypes = (TypeScriptDateTimeType[])Enum.GetValues(typeof(TypeScriptDateTimeType));
    }

    [BenchmarkAttribute]
    public void GetValues_Cast_ToArray()
    {
        TypeScriptDateTimeType[] dateTimeTypes = Enum.GetValues(typeof(TypeScriptDateTimeType)).Cast<TypeScriptDateTimeType>().ToArray();
    }
}

void Main() => BenchmarkRunner.Run<Benchmark>();

// Summary

BenchmarkDotNet v0.13.12, Windows 10 (10.0.19045.4170/22H2/2022Update) Intel Core i7-10700 CPU 2.90GHz, 1 CPU, 16 logical and 8 physical cores .NET SDK 8.0.202 [Host] : .NET 8.0.3 (8.0.324.11423), X64 RyuJIT AVX2

Job=.NET 8.0 Runtime=.NET 8.0

Method Mean Error StdDev Gen0 Allocated
GetNames 517.95 ns 9.369 ns 7.824 ns 0.0372 312 B
GetValues_Explicit_Cast 96.60 ns 1.789 ns 1.674 ns 0.0057 48 B
GetValues_Cast_ToArray 137.05 ns 2.430 ns 2.154 ns 0.0114 96 B
RicoSuter commented 3 months ago

Is this really the same? This is in the UI, does it even matter?

testfirstcoder commented 3 months ago

Is this really the same?


{
var dateTimeTypesInitial = Enum
.GetNames(typeof(TypeScriptDateTimeType))
.Select(t => (TypeScriptDateTimeType)Enum.Parse(typeof(TypeScriptDateTimeType), t))
.ToArray();
var dateTimeTypesRefactored = (TypeScriptDateTimeType[])Enum.GetValues(typeof(TypeScriptDateTimeType));

Debug.Assert(dateTimeTypesInitial.GetType().Equals(dateTimeTypesRefactored.GetType()));

Debug.Assert(dateTimeTypesInitial.SequenceEqual(dateTimeTypesRefactored));

}



> does it even matter?

Not sure if but it's concise and more readable.