Skip to content

Instantly share code, notes, and snippets.

@JamesKim2998
Created October 10, 2017 08:58
Show Gist options
  • Save JamesKim2998/d7f7a7f212a41929fee356ff09283133 to your computer and use it in GitHub Desktop.
Save JamesKim2998/d7f7a7f212a41929fee356ff09283133 to your computer and use it in GitHub Desktop.
Performance comparison between int and enum.
using System;
using UnityEngine;
using UnityEngine.UI;
/******** Result *********
* TestIntConversion: .0032730
* TestEnumConversion: .0029910
* TestIntOp: .0027300
* TestEnumOp: .0030000 <- always lose :(
* TestIntToString: .3037160
* TestEnumToString: 2.7711720
* TestEnumToStringCustom: .3533840
* TestEnumToStringCustomInline: .3253510
**************************/
public enum Meter
{
}
public class EnumAsMetricBenchmark : MonoBehaviour
{
const int _iteration = 100000;
public Text Text;
public void Test()
{
_text = Text;
_text.text = "";
Test(TestIntConversion);
Test(TestEnumConversion);
Test(TestIntOp);
Test(TestEnumOp);
Test(TestIntToString);
Test(TestEnumToString);
Test(TestEnumToStringCustom);
Test(TestEnumToStringCustomInline);
}
static Text _text;
static void TestIntConversion(int i)
{
var x = i;
var y = (int) x;
}
static void TestEnumConversion(int i)
{
var x = default(Meter);
var y = (int) x;
}
static void TestIntOp(int i, int j)
{
var a = i;
var b = j;
var c = a + b;
}
static void TestEnumOp(int i, int j)
{
var a = (Meter) i;
var b = j;
var c = a + b;
}
static void TestIntToString(int i)
{
i.ToString();
}
static void TestEnumToString(int i)
{
var a = (Meter) i;
a.ToString();
}
static void TestEnumToStringCustom(int i)
{
var a = (Meter) i;
a.ToStr();
}
static void TestEnumToStringCustomInline(int i)
{
var a = (Meter) i;
((int) a).ToString();
}
static void Test(Action<int> func)
{
var startTime = DateTime.Now;
for (var i = 0; i != _iteration; ++i)
func(i);
var doneTime = DateTime.Now;
_text.text += func.Method.Name + ": " + (doneTime - startTime) + "\n";
}
static void Test(Action<int, int> func)
{
var startTime = DateTime.Now;
for (var i = 0; i != _iteration; ++i)
func(i, i / 3);
var doneTime = DateTime.Now;
_text.text += func.Method.Name + ": " + (doneTime - startTime) + "\n";
}
}
public static class ExtensionMethods
{
public static string ToStr(this Meter thiz)
=> ((int) thiz).ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment