Reputation: 886
Taken example from w3school:
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
and
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
does explicit casting add extra overhead, especially for large number/array of numbers? or it is same as implicit casting?
I had to ask this for academic reason, and also would like to explicitly casting my objects and interfaces everywhere to add clarity on code base.
Edit :
add animal example:
IAnimal animal = (IAnimal) dog;
IAnimal animal = dog;
Upvotes: 0
Views: 1417
Reputation: 23228
does explicit casting add extra overhead, especially for large number/array of numbers? or it is same as implicit casting?
You can refer to SharpLab to see the differences under the hood in IL. As you can see, the logic is pretty same (except the types, of course, because you are using the different types)
.method public hidebysig
instance float64 AutoCast () cil managed
{
.maxstack 8
IL_0000: ldc.i4.s 9
IL_0002: conv.r8
IL_0003: ret
} // end of method C::AutoCast
.method public hidebysig
instance int32 ManualCast () cil managed
{
.maxstack 8
IL_0000: ldc.r8 9.78
IL_0009: conv.i4
IL_000a: ret
} // end of method C::ManualCast
Or even refer to ASM code
C.AutoCast()
L0000: sub esp, 0x8
L0003: vzeroupper
L0006: vmovsd xmm0, qword [0x14540488]
L000e: vmovsd [esp], xmm0
L0013: fld qword [esp]
L0016: add esp, 0x8
L0019: ret
C.ManualCast()
L0000: mov eax, 0x9
L0005: ret
As you can see, cast double
to int
just moves value and return an integral part, int
to double
more complicated. As a result of that, you can see the different benchmark results.
Of course, it depends on used CLR and .NET version (there are a lot improvements in .NET Core and some hardware intrinsics were added as well). I've run it using .NET Core and CoreCLR, in .NET Framework you'll see the different results.
You can check the exact behavior on your environment with your code (at least because you've asked a question for academic reason)
Upvotes: 2