Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active May 2, 2021 15:56
Show Gist options
  • Save guitarrapc/e518788cb3918fb9259ce24e06796073 to your computer and use it in GitHub Desktop.
Save guitarrapc/e518788cb3918fb9259ce24e06796073 to your computer and use it in GitHub Desktop.
void Main()
{
var summary = BenchmarkRunner.Run<BenchmarkSum>();
}
[BenchmarkDotNet.Attributes.MemoryDiagnoser]
public class BenchmarkSum
{
[Benchmark]
public void Slow()
{
SumSlow(8192, 8, 9);
}
[Benchmark]
public void Fast()
{
SumFast(8192, 8, 9);
}
[Benchmark]
public void FastAlloc()
{
SumFastAlloc(8192, 8, 9);
}
[Benchmark]
public void M2()
{
M2(8192, 8, 9);
}
int SumSlow(int size, int x, int y)
{
int sum = 0;
int hoist = x * y;
for (int i = 0; i < size; i++)
{
try { sum += hoist; }
catch { }
}
return sum;
}
int SumFast(int size, int x, int y)
{
int sum = 0;
int hoist = x * y;
int[] tmp = new int[1];
for (int i = 0; i < size; i++)
{
try
{
tmp[0] = hoist;
sum += tmp[0];
}
catch { }
}
return sum;
}
int SumFastAlloc(int size, int x, int y)
{
int sum = 0;
int hoist = x * y;
Span<int> tmp = stackalloc int[1];
for (int i = 0; i < size; i++)
{
try
{
tmp[0] = hoist;
sum += tmp[0];
}
catch { }
}
return sum;
}
int M2(int size, int x, int y)
{
int sum = 0;
Span<int> tmp = stackalloc int[1];
tmp[0] = x* y;
for (int i = 0; i < size; i++)
{
try {
sum += tmp[0];}
catch {}
}
return sum;
}
}
@guitarrapc
Copy link
Author

guitarrapc commented May 2, 2021

image
image

@guitarrapc
Copy link
Author

guitarrapc commented May 2, 2021

Added Stackalloc.

image
image

@guitarrapc
Copy link
Author

guitarrapc commented May 2, 2021

change move.

image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment