|
型変換でCTypeよりDirectCastの方が高速という事はよく聞くのですが、実際どのようになっているのかは理解していなかったので、検証も含め調査しました。
Shared Sub Main()
Dim a As Object = 0
Dim b As Object = 0
Dim c As Double = DirectCast(a, Integer)
Dim d As Double = CType(b, Integer)
End Sub
をビルドしたexeをildasmでILコードに逆アセンブルします。
.method public static void Main() cil managed
{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 )
// コード サイズ 38 (0x26)
.maxstack 1
.locals init ([0] object a,
[1] object b,
[2] float64 c,
[3] float64 d)
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: box [mscorlib]System.Int32
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: box [mscorlib]System.Int32
IL_000e: stloc.1
IL_000f: ldloc.0
IL_0010: unbox [mscorlib]System.Int32
IL_0015: ldobj [mscorlib]System.Int32
IL_001a: conv.r8
IL_001b: stloc.2
IL_001c: ldloc.1
IL_001d: call int32 [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.Conversions::ToInteger(object)
IL_0022: conv.r8
IL_0023: stloc.3
IL_0024: nop
IL_0025: ret
} // end of method Class1::Main
DirectCastの方は.NET Frameworkの[unbox]を使用しているのに対し、CTypeはMicrosoft.VisualBasic.CompilerServices.ConversionsのToInteger関数をコールしている事が解ります。
MSDNによるとDirectCast使用時はVisual Basic のランタイム ヘルパー ルーチン(上記)を変換に使用しない為、高速なのだそうです。
For i As Integer = 0 To 99999999
Dim a As Object = 0
Dim c As Double = CType(a, Integer) ' or DirectCast
Next
で試したところ、DirectCastの場合は約1秒、CTypeの場合は約2.5秒かかりました。
特に制約がない場合は、DirectCastを使用したほうがやはり高速なようです。
注意点に関しては
http://msdn.microsoft.com/ja-jp/library/7k6y2h6x(v=vs.80).aspx
を参照してください。
|