Skip to content

Instantly share code, notes, and snippets.

@malkia
Created April 26, 2011 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malkia/942951 to your computer and use it in GitHub Desktop.
Save malkia/942951 to your computer and use it in GitHub Desktop.
some test
// x64
//
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace GenericSpeedTest
{
static class Program
{
private static T GenericBound<T>(T val, T min, T max) where T : IComparable<T>
{
T result = val;
if (result.CompareTo(min) < 0)
{
result = min;
}
if (result.CompareTo(max) > 0)
{
result = max;
}
return result;
}
private static int IntegerBound(int val, int min, int max)
{
#if true
if (val < min)
return min;
if (val > max)
return max;
return val;
#else
int result = val;
if (result.CompareTo(min) < 0)
{
result = min;
}
if (result.CompareTo(max) > 0)
{
result = max;
}
return result;
#endif
}
private static void GenericMathSpeedTest()
{
{
Console.WriteLine(GenericBound<int>(0, 0, 1));
Stopwatch s = new Stopwatch();
s.Start();
int sum = 0;
for (int i = 0; i < 128 * 1024 * 1024; ++i)
{
int t = i;
sum += GenericBound<int>(t, -5, 5);
}
s.Stop();
MessageBox.Show("Generic math took " + s.Elapsed.TotalSeconds + " seconds. " + sum);
}
{
Stopwatch s = new Stopwatch();
s.Start();
int sum = 0;
for (int i = 0; i < 128 * 1024 * 1024; ++i)
{
int t = i;
sum += IntegerBound(t, -5, 5);
}
s.Stop();
MessageBox.Show("Manually instantiated math took " + s.Elapsed.TotalSeconds + " seconds. " + sum);
}
}
#if true
private struct MyType
{
public MyType(int _n)
{
n = 1;
}
public int n;
}
#else
class MyType
{
public int n = 1;
}
#endif
private static T GenericNew<T>() where T : new()
{
return new T();
}
private static MyType ManualNew()
{
MyType val;
val.n = 1;
return val;
}
private static void GenericNewSpeedTest()
{
{
Stopwatch s = new Stopwatch();
int sum = 0;
s.Start();
for (int i = 0; i < 128 * 1024 * 1024; ++i)
{
sum += GenericNew<MyType>().n;
}
s.Stop();
MessageBox.Show("Generic new took " + s.Elapsed.TotalSeconds + " seconds. " + sum);
}
{
Stopwatch s = new Stopwatch();
int sum = 0;
s.Start();
for (int i = 0; i < 128 * 1024 * 1024; ++i)
{
sum += ManualNew().n;
}
s.Stop();
MessageBox.Show("Manually instantiated new took " + s.Elapsed.TotalSeconds + " seconds. " + sum);
}
}
static void Main()
{
GenericMathSpeedTest();
GenericNewSpeedTest();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment