Skip to content

Enum boxing optimizations (UnitKey) #1507

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="System.Runtime.CompilerServices.Unsafe" Version="6.1.0" />
<PackageVersion Include="BenchmarkDotNet" Version="0.14.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System;
using System.Globalization;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using UnitsNet.Units;

namespace UnitsNet.Benchmark.Conversions.FromString;

[MemoryDiagnoser]
[SimpleJob(RuntimeMoniker.Net48)]
[SimpleJob(RuntimeMoniker.Net80)]
public class QuantityFromStringBenchmarks
{
private static readonly CultureInfo Culture = CultureInfo.InvariantCulture;
private static readonly string ValueToParse = 123.456.ToString(Culture);

private readonly Random _random = new(42);
private string[] _quantitiesToParse;

[Params(1000)]
public int NbAbbreviations { get; set; }

[GlobalSetup(Target = nameof(FromMassString))]
public void PrepareMassStrings()
{
// can't have "mg" or "g" (see Acceleration.StandardGravity) and who knows what more...
_quantitiesToParse = _random.GetItems(["kg", "lbs", "Mlbs"], NbAbbreviations).Select(abbreviation => $"{ValueToParse} {abbreviation}").ToArray();
}

[GlobalSetup(Target = nameof(FromVolumeUnitAbbreviation))]
public void PrepareVolumeStrings()
{
_quantitiesToParse = _random.GetItems(["ml", "l", "cm³", "m³"], NbAbbreviations).Select(abbreviation => $"{ValueToParse} {abbreviation}").ToArray();;
}

[GlobalSetup(Target = nameof(FromPressureUnitAbbreviation))]
public void PreparePressureUnits()
{
_quantitiesToParse = _random.GetRandomAbbreviations<PressureUnit>(UnitsNetSetup.Default.UnitAbbreviations, NbAbbreviations).Select(abbreviation => $"{ValueToParse} {abbreviation}").ToArray();;
}

[GlobalSetup(Target = nameof(FromVolumeFlowUnitAbbreviation))]
public void PrepareVolumeFlowUnits()
{
// can't have "bpm" (see Frequency)
_quantitiesToParse =
_random.GetItems(
UnitsNetSetup.Default.UnitAbbreviations.GetAllUnitAbbreviationsForQuantity(typeof(VolumeFlowUnit)).Where(x => x != "bpm").ToArray(),
NbAbbreviations).Select(abbreviation => $"{ValueToParse} {abbreviation}").ToArray();
}

[Benchmark(Baseline = true)]
public IQuantity FromMassString()
{
IQuantity quantity = null;
foreach (var quantityString in _quantitiesToParse)
{
quantity = Quantity.Parse(Culture, typeof(Mass), quantityString);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromVolumeUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var quantityString in _quantitiesToParse)
{
quantity = Quantity.Parse(Culture, typeof(Volume), quantityString);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromPressureUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var quantityString in _quantitiesToParse)
{
quantity = Quantity.Parse(Culture, typeof(Pressure), quantityString);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromVolumeFlowUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var quantityString in _quantitiesToParse)
{
quantity = Quantity.Parse(Culture, typeof(VolumeFlow), quantityString);
}

return quantity;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using System;
using System.Globalization;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using UnitsNet.Units;

namespace UnitsNet.Benchmark.Conversions.FromString;

[MemoryDiagnoser]
[SimpleJob(RuntimeMoniker.Net48)]
[SimpleJob(RuntimeMoniker.Net80)]
public class QuantityFromUnitAbbreviationBenchmarks
{
private static readonly CultureInfo Culture = CultureInfo.InvariantCulture;
private readonly Random _random = new(42);
private string[] _massUnits;
private string[] _pressureUnits;
private string[] _volumeFlowUnits;
private string[] _volumeUnits = [];

[Params(1000)]
public int NbAbbreviations { get; set; }

[GlobalSetup(Target = nameof(FromMassUnitAbbreviation))]
public void PrepareMassUnits()
{
// can't have "mg" or "g" (see Acceleration.StandardGravity) and who knows what more...
_massUnits = _random.GetItems(["kg", "lbs", "Mlbs"], NbAbbreviations);
}

[GlobalSetup(Target = nameof(FromVolumeUnitAbbreviation))]
public void PrepareVolumeUnits()
{
_volumeUnits = _random.GetItems(["ml", "l", "cm³", "m³"], NbAbbreviations);
}

[GlobalSetup(Target = nameof(FromPressureUnitAbbreviation))]
public void PreparePressureUnits()
{
_pressureUnits = _random.GetRandomAbbreviations<PressureUnit>(UnitsNetSetup.Default.UnitAbbreviations, NbAbbreviations);
}

[GlobalSetup(Target = nameof(FromVolumeFlowUnitAbbreviation))]
public void PrepareVolumeFlowUnits()
{
// can't have "bpm" (see Frequency)
_volumeFlowUnits =
_random.GetItems(
UnitsNetSetup.Default.UnitAbbreviations.GetAllUnitAbbreviationsForQuantity(typeof(VolumeFlowUnit)).Where(x => x != "bpm").ToArray(),
NbAbbreviations);
}

[Benchmark(Baseline = true)]
public IQuantity FromMassUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var unitToParse in _massUnits)
{
quantity = Quantity.FromUnitAbbreviation(Culture, 1, unitToParse);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromVolumeUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var unitToParse in _volumeUnits)
{
quantity = Quantity.FromUnitAbbreviation(Culture, 1, unitToParse);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromPressureUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var unitToParse in _pressureUnits)
{
quantity = Quantity.FromUnitAbbreviation(Culture, 1, unitToParse);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromVolumeFlowUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var unitToParse in _volumeFlowUnits)
{
quantity = Quantity.FromUnitAbbreviation(Culture, 1, unitToParse);
}

return quantity;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;

namespace UnitsNet.Benchmark.Conversions.FromString;

[MemoryDiagnoser]
[SimpleJob(RuntimeMoniker.Net48)]
[SimpleJob(RuntimeMoniker.Net80)]
public class QuantityFromUnitNameBenchmarks
{
private readonly Random _random = new(42);
private string[] _unitNames;

[Params(1000)]
public int NbAbbreviations { get; set; }

[GlobalSetup(Target = nameof(FromMassUnitName))]
public void PrepareMassUnits()
{
_unitNames = _random.GetItems(Mass.Info.UnitInfos.Select(x => x.Name).ToArray(), NbAbbreviations);
}

[GlobalSetup(Target = nameof(FromVolumeUnitAbbreviation))]
public void PrepareVolumeUnits()
{
_unitNames = _random.GetItems(Volume.Info.UnitInfos.Select(x => x.Name).ToArray(), NbAbbreviations);
}

[GlobalSetup(Target = nameof(FromPressureUnitAbbreviation))]
public void PreparePressureUnits()
{
_unitNames = _random.GetItems(Pressure.Info.UnitInfos.Select(x => x.Name).ToArray(), NbAbbreviations);
}

[GlobalSetup(Target = nameof(FromVolumeFlowUnitAbbreviation))]
public void PrepareVolumeFlowUnits()
{
_unitNames = _random.GetItems(VolumeFlow.Info.UnitInfos.Select(x => x.Name).ToArray(), NbAbbreviations);
}

[Benchmark(Baseline = true)]
public IQuantity FromMassUnitName()
{
IQuantity quantity = null;
foreach (var unitName in _unitNames)
{
quantity = Quantity.From(1, nameof(Mass), unitName);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromVolumeUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var unitName in _unitNames)
{
quantity = Quantity.From(1, nameof(Volume), unitName);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromPressureUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var unitName in _unitNames)
{
quantity = Quantity.From(1, nameof(Pressure), unitName);
}

return quantity;
}

[Benchmark(Baseline = false)]
public IQuantity FromVolumeFlowUnitAbbreviation()
{
IQuantity quantity = null;
foreach (var unitName in _unitNames)
{
quantity = Quantity.From(1, nameof(VolumeFlow), unitName);
}

return quantity;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.Globalization;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using UnitsNet.Units;

namespace UnitsNet.Benchmark.Conversions.ToString;

[MemoryDiagnoser]
[SimpleJob(RuntimeMoniker.Net48)]
[SimpleJob(RuntimeMoniker.Net80)]
public class ToStringWithDefaultPrecisionBenchmarks
{
private static readonly double Value = 123.456;
private readonly Random _random = new(42);

private Mass[] _masses = [];
private VolumeFlow[] _volumeFlows = [];

[Params(1000)]
public int NbConversions { get; set; }

[Params("G", "S", "E", "N", "A")]
public string Format { get; set; }

[GlobalSetup(Target = nameof(MassToString))]
public void PrepareMassesToTest()
{
_masses = _random.GetRandomQuantities<Mass, MassUnit>(Value, Mass.Units, NbConversions).ToArray();
}

[GlobalSetup(Target = nameof(VolumeFlowToString))]
public void PrepareVolumeFlowsToTest()
{
_volumeFlows = _random.GetRandomQuantities<VolumeFlow, VolumeFlowUnit>(Value, VolumeFlow.Units, NbConversions).ToArray();
}

[Benchmark(Baseline = true)]
public void MassToString()
{
foreach (Mass quantity in _masses)
{
var result = quantity.ToString(Format, CultureInfo.InvariantCulture);
}
}

[Benchmark]
public void VolumeFlowToString()
{
foreach (VolumeFlow quantity in _volumeFlows)
{
var result = quantity.ToString(Format, CultureInfo.InvariantCulture);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public double ConvertFromQuantity()
[GlobalSetup]
public void PrepareTo_ConvertWith_FullyCachedFrozenDictionary()
{
var nbQuantities = Quantity.Infos.Length;
var nbQuantities = Quantity.Infos.Count;
}

}
3 changes: 2 additions & 1 deletion UnitsNet.Benchmark/UnitsNet.Benchmark.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>net8.0;net48</TargetFrameworks>
<LangVersion>preview</LangVersion>
<Version>4.0.0.0</Version>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyTitle>UnitsNet.Benchmark</AssemblyTitle>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ protected virtual Enum FindUnit(string unitAbbreviation, out QuantityInfo quanti
/// <returns>The default abbreviation as provided by the associated <see cref="UnitAbbreviationsCache" /></returns>
protected string GetUnitAbbreviation(Enum unit)
{
return _abbreviations.GetDefaultAbbreviation(unit.GetType(), Convert.ToInt32(unit), CultureInfo.InvariantCulture);
return _abbreviations.GetDefaultAbbreviation(unit, CultureInfo.InvariantCulture);
}

/// <summary>
Expand Down
Loading