Skip to content

Instantly share code, notes, and snippets.

@rpgmaker
Last active December 25, 2015 18:19
Show Gist options
  • Save rpgmaker/7019767 to your computer and use it in GitHub Desktop.
Save rpgmaker/7019767 to your computer and use it in GitHub Desktop.
Test integer to string
static void Test(string name, Action action) {
var count = 10000;
var stopWatch = new Stopwatch();
stopWatch.Start();
for (var i = 0; i < count; i++)
action();
stopWatch.Stop();
Console.WriteLine("Iteration: {0}", count);
Console.WriteLine("Completed {0} in Avg {1} Milliseconds", name, stopWatch.ElapsedMilliseconds);
Console.WriteLine();
}
static NumberFormatInfo currentCulture = NumberFormatInfo.CurrentInfo;
static IFormatProvider culture = CultureInfo.CurrentCulture;
public delegate string FastConvert(int value, NumberFormatInfo culture);
var asm = AppDomain.CurrentDomain.GetAssemblies().First(x => x.FullName.Contains("mscorlib"));
var numberType = asm.GetTypes().First(x => x.Name == "Number");
var numberMethod = numberType.GetMethods().FirstOrDefault(x => x.Name == "FormatInt32");
var myNumber = 1000;
var myStr = (string)numberMethod.Invoke(null, new object[] { myNumber, default(string), currentCulture });
var mm = new DynamicMethod("toNumber", typeof(string), new[] { typeof(int), typeof(NumberFormatInfo) }, true);
var il = mm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Call, numberMethod);
il.Emit(OpCodes.Ret);
var func = mm.CreateDelegate(typeof(FastConvert)) as FastConvert;
Test("Int32ToString", () =>
{
for (var i = 0; i < 1000; i++) {
var sx = 10.ToString();
}
});
Test("Int32ToStringWithCultureDelegate", () =>
{
for (var i = 0; i < 1000; i++) {
var sx = func(10, currentCulture);
//var ix = "";
}
});
Test("Int32ToStringWithCulture", () =>
{
for (var i = 0; i < 1000; i++) {
var sx = 10.ToString(culture);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment