Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,56 +3,58 @@

namespace SwitchVsIfElsePerformanceTests.BenchmarkTests;

[InProcess]
public class PatternMatchingVsComplexIfElseBenchmarkTests
{
private object[] _shapes = {
private readonly object[] _shapes =
[
new Circle { Radius = 12 },
new Circle { Radius = 4 },
new Rectangle { Width = 4, Height = 4 },
new Rectangle { Width = 4, Height = 10 },
new Line { Length = 10 },
};

[Params(1000)]
public int N;

];

[Benchmark]
public void IfElseWithComplexConditions()
public int IfElseWithComplexConditions()
{
string shapeName;
var totalLength = 0;

foreach (object shape in _shapes)
{
shapeName = ClassifyShapeWithIfElse(shape);
totalLength += ClassifyShapeWithIfElse(shape).Length;
}

return totalLength;
}

[Benchmark]
public void SwitchExpressionWithPatternMatching()
public int SwitchExpressionWithPatternMatching()
{
string shapeName;
var totalLength = 0;

foreach (object shape in _shapes)
{
shapeName = ClassifyShapeWithPatternMathing(shape);
totalLength += ClassifyShapeWithPatternMatching(shape).Length;
}

return totalLength;
}

private string ClassifyShapeWithIfElse(object shape)
private static string ClassifyShapeWithIfElse(object shape)
{
if (shape is Circle)
if (shape is Circle circle)
{
if (((Circle)shape).Radius > 10)
if (circle.Radius > 10)
{
return "Large Circle";
}

return "Circle";
}
if (shape is Rectangle)

if (shape is Rectangle rectangle)
{
var rectangle = shape as Rectangle;

if (rectangle.Height == rectangle.Width)
{
return "Square";
Expand All @@ -63,9 +65,8 @@ private string ClassifyShapeWithIfElse(object shape)

return "Unknown Shape";
}


private string ClassifyShapeWithPatternMathing(object shape) =>

private static string ClassifyShapeWithPatternMatching(object shape) =>
shape switch
{
Circle { Radius: > 10 } => "Large Circle",
Expand All @@ -74,4 +75,4 @@ private string ClassifyShapeWithPatternMathing(object shape) =>
Rectangle => "Rectangle",
_ => "Unknown Shape"
};
}
}
Loading
Loading