Skip to content

Instantly share code, notes, and snippets.

@mntone
Last active December 20, 2015 14:48
Show Gist options
  • Save mntone/6149385 to your computer and use it in GitHub Desktop.
Save mntone/6149385 to your computer and use it in GitHub Desktop.
型比較からのキャストして情報を扱う速度。 (1) o.GetType() == typeof( Obj ) + var obj = ( Obj )o (2) o is Obj + var obj = ( Obj )o (3) var obj = o as Obj + obj != null ※ .NET Framework 4.5.1 (Windows 8.1, Core i7-2620M, RAM 8 GB (+ 4 GB on SSD)) で実行。(1)<(2)<(3) と時間がかかる。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace CheckingPatternTest
{
class Program
{
static void Main( string[] args )
{
const long c = 1000000000;
var watch = Stopwatch.StartNew();
watch.Stop();
watch.Reset();
var b = new Test();
var a = ( Base )b;
watch.Start();
for( int i = 0; i < c; i++ )
{
if( a.GetType() == typeof( Test ) )
{
var testobj = ( Test )a;
testobj.A = "ok";
}
}
watch.Stop();
Console.WriteLine( "a.GetType() == typeof( Test ), var testobj = ( Test )a: {0}", watch.Elapsed );
watch.Start();
for( int i = 0; i < c; i++ )
{
if( a is Test )
{
var testobj = ( Test )a;
testobj.A = "ok";
}
}
watch.Stop();
Console.WriteLine( "a is Test, var testobj = ( Test )a: {0}", watch.Elapsed );
watch.Start();
for( int i = 0; i < c; i++ )
{
var testobj = a as Test;
if( testobj != null )
{
testobj.A = "ok";
}
}
watch.Stop();
Console.WriteLine( "testobj = a as Test, testobj != null: {0}", watch.Elapsed );
Console.ReadLine();
}
class Base
{
public string A { get; set; }
}
class Test: Base
{
public string B { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment