CSharp · Console
using System;
using System.Text.RegularExpressions;
using System.Reflection;
public class Program
{
public static void Main()
{
int max = 10000;
TimerExpression("TryParse",
() =>
{
for (int i = 0; i < max; i++)
{
int value = 0;
Int32.TryParse(i.ToString(), out value);
}
});
TimerExpression("Regex",
() =>
{
for (int i = 0; i < max; i++)
{
Regex.IsMatch(i.ToString(), @"\d");
}
});
TimerExpression("PHP IsNumeric",
() =>
{
for (int i = 0; i < max; i++)
{
i.ToString().IsNumeric();
}
});
TimerExpression("Reflections TryParse",
() =>
{
for (int i = 0; i < max; i++)
{
i.ToString().ParseAs<int>(0);
}
});
}
public static void TimerExpression(string label, Action call)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
call.DynamicInvoke();
watch.Stop();
System.Console.WriteLine(label + " " + watch.ElapsedMilliseconds.ToString());
}
}
public static class StringExtension
{
public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue)
{
var type = typeof(TOutput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder, new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return defaultValue;
var arguments = new object[] { value, null };
return ((bool)tryParseMethod.Invoke(null, arguments)) ? (TOutput)arguments[1] : defaultValue;
}
static readonly Regex _isNumericRegex =
new Regex("^(" +
/*Hex*/ @"0x[0-9a-f]+" + "|" +
/*Bin*/ @"0b[01]+" + "|" +
/*Oct*/ @"0[0-7]*" + "|" +
/*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" +
")$");
public static bool IsNumeric(this string value)
{
return _isNumericRegex.IsMatch(value);
}
}