Skip to content

Commit

Permalink
Added prototype of allocation free Match method (#146)
Browse files Browse the repository at this point in the history
There is a simple Match method, which by design consumes 130x more CPU
and allocates 48 bytes with each call.
I strongly recommend to document this behavior or add implementation for
simple transformation, which directly returns mapped value.
As you can see in this code, which si more as prototype or
documentation, than real improvement, it is feasible to reduce the
method overhead.

Recommendations:
* Equal method in the function buddy causes boxing to object e.g.
allocations
* When delegate is not needed to transform result, than simple overload
can be used
* != is no longer recommended way for null comparison, since it can be
overloaded, use "is not null" instead

Not expecting this PR to be merged, should be used as reference only.
  • Loading branch information
KaliCZ authored Oct 3, 2023
2 parents 5c257f5 + e812d82 commit 451022f
Show file tree
Hide file tree
Showing 3 changed files with 1,356 additions and 1 deletion.
46 changes: 46 additions & 0 deletions src/FuncSharp.Benchmarks/Object/IfMatchBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using BenchmarkDotNet.Attributes;

namespace FuncSharp.Benchmarks;

[MemoryDiagnoser]
public class IfMatchBenchmarks
{
// Last Result - 14.9.2023 - 5.959 ns - 48 B
[Benchmark]
public void MapTrue()
{
var result = this.Map(true);
}

// Last Result - 14.9.2023 - 0.0046 ns - 0 B
[Benchmark]
public void MapValueTrue()
{
var result = this.MapValue(true);
}

// Last Result - 14.9.2023 - 0.0012 ns - 0 B
[Benchmark]
public void IfTrue()
{
var result = this.IF(true);
}

public int Map(bool source)
{
return source.Match(true, a => 5, a => 11);
}

public int MapValue(bool source)
{
return source.Match(true, 5, 11);
}

public int IF(bool source)
{
if (source)
return 5;

return 11;
}
}
Loading

0 comments on commit 451022f

Please sign in to comment.