这个问题已经得到了很好的回答,但迄今为止,这一问题一直没有足够数目。
Over 100000000 iterations
AS : Failure 00:00:00.9282403
Cast : Failure 00:00:00.9868966
AS : Success 00:00:00.9350227
Cast : Success 00:00:01.1382759
这些数字始终如一地回过来。
我想指出,从这些数字中得出的唯一结论是,从业绩的角度来看,选择其中一种方法与另一个“
之后,上述数字大多是有理由的。
“由于”失败的时间比成功要长。 在成功方面没有发生,价值可以像现在一样使用,或者简单复制。 否则,就要求翻一番。
“Cast”在失败时越快,就叫“是”,而且没有做。 成功速度要慢得多,但要求“是”,然后是 cast。
但 我感到惊讶的是,种姓的失败比AS失败要长。
<><>Edit>/strong>
根据要求,在审判/捕获区投放的数字
Over 100000000 iterations
Catch : Failure 05.05:00:00 // approximately, because I didn t hang around
Catch : Success 00:00:01.4000952
编制第一批数字的法典
class Program
{
const int ITERATION_COUNT = 100000000;
private static UInt64 stringCount = 0;
private static UInt64 objectCount = 0;
static void Main(string[] args)
{
Console.WriteLine("Over {0} iterations ", ITERATION_COUNT);
string s = "Hello";
object o = new Int32();
RunTest("AS : Failure {0}", TestAs, o);
RunTest("Cast : Failure {0}", TestIs_And_Cast, o);
RunTest("AS : Success {0}", TestAs, s);
RunTest("Cast : Success {0}", TestIs_And_Cast, s);
Console.WriteLine("Press any key to stop");
Console.ReadKey();
}
private static void RunTest(string testDescription, Action<object> testToRun, object arg)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < ITERATION_COUNT; i++)
testToRun(arg);
sw.Stop();
Console.WriteLine(testDescription, sw.Elapsed);
}
static void TestAs(object obj)
{
string s = obj as string;
if (s != null)
stringCount++;
else
objectCount++;
}
static void TestIs_And_Cast(object obj)
{
string s = null;
if (obj is string)
{
s = (string)obj;
stringCount++;
}
else
objectCount++;
}
}