Last active
July 13, 2023 13:55
-
-
Save ptupitsyn/3e69d0938f02e8ec95dfe67d608a6561 to your computer and use it in GitHub Desktop.
C# checked cast vs Convert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net7.0</TargetFramework> | |
<ImplicitUsings>enable</ImplicitUsings> | |
<Nullable>enable</Nullable> | |
</PropertyGroup> | |
<ItemGroup> | |
<PackageReference Include="BenchmarkDotNet" Version="0.13.6" /> | |
</ItemGroup> | |
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
// | Method | Val | Mean | Error | StdDev | Ratio | RatioSD | | |
// |------------ |----------- |--------------:|-----------:|-----------:|------:|--------:| | |
// | CheckedCast | 1 | 0.3265 ns | 0.0030 ns | 0.0028 ns | 1.00 | 0.00 | | |
// | ConvertTo | 1 | 1.1499 ns | 0.0044 ns | 0.0042 ns | 3.52 | 0.03 | | |
// | | | | | | | | | |
// | CheckedCast | 2147483647 | 6,430.8317 ns | 10.7705 ns | 10.0747 ns | 1.00 | 0.00 | | |
// | ConvertTo | 2147483647 | 6,405.4382 ns | 20.2827 ns | 18.9725 ns | 1.00 | 0.00 | | |
BenchmarkRunner.Run<Bench>(); | |
public class Bench | |
{ | |
[Params(1, int.MaxValue)] public int Val { get; set; } | |
[Benchmark(Baseline = true)] | |
public short CheckedCast() | |
{ | |
try | |
{ | |
return checked((short)Val); | |
} | |
catch (OverflowException) | |
{ | |
return 0; | |
} | |
} | |
[Benchmark] | |
public short ConvertTo() | |
{ | |
try | |
{ | |
return Convert.ToInt16(Val); | |
} | |
catch (OverflowException) | |
{ | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment