Skip to content

Instantly share code, notes, and snippets.

@GeirGrusom
Created December 17, 2014 10:14
Show Gist options
  • Save GeirGrusom/ce12a207fcfcf423a3c0 to your computer and use it in GitHub Desktop.
Save GeirGrusom/ce12a207fcfcf423a3c0 to your computer and use it in GitHub Desktop.
Performance difference between to different expressions for the same thing
using System;
using System.Diagnostics;
namespace Bleh
{
class Program
{
static void Main()
{
for (int i = 0; i < 5; i++)
{
var a = A();
var b = B();
Debugger.Log(0, "Performance", string.Format("The time difference is {0} ms.\r\n", (Math.Abs(b - a) / (double)Stopwatch.Frequency) * 1000));
}
}
public static unsafe long B()
{
var watch = Stopwatch.StartNew();
int* data = stackalloc int[10000];
int* ptr = data;
for (int i = 0; i < 10000; i++)
{
*(ptr++) = 123;
}
watch.Stop();
Debugger.Log(0, "Performance", string.Format("*(ptr++) = 123 took {0} ms.\r\n", (watch.ElapsedTicks / (double)Stopwatch.Frequency) * 1000 ));
return watch.ElapsedTicks;
}
public static unsafe long A()
{
var watch = Stopwatch.StartNew();
int* data = stackalloc int[10000];
int* ptr = data;
for (int i = 0; i < 10000; i++)
{
*ptr = 123;
ptr++;
}
watch.Stop();
Debugger.Log(0, "Performance", string.Format("*ptr = 123; ptr++ took {0} ms.\r\n", (watch.ElapsedTicks / (double)Stopwatch.Frequency) * 1000));
return watch.ElapsedTicks;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment