The cost of the "Go" C # type conversion

Source: Internet
Author: User

This article goes from:

Http://www.codeproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in

Type Casting impact over execution performance in C #Emilio Guijarro, 2004 160.4K 2
4.59 (votes)
Rate: Vote 1vote 2vote 3vote 4vote 5
This article analyzes the most common type casting situations in C # and the compiler behaviour in them.Introduction

Explicit and implicit type casting is a common programming topic for almost any imperative programming language. Most C, C + +, or Pascal programmers care about efficiency and speed of their code; But those managed programming environments, such as Java, Visual Basic, or C # rely all the optimizing tasks on the compiler and the runtime environment.

This can is a good approach in many cases, but managed languages is becoming more and more popular also for High-performa NCE applications where the knowledge of the language, compiler, and runtime environment can enhance a program's quality an D speed.

This article analyzes the most common type casting situations and the compiler behavior in them. We is going to study the MSIL generated code, and not the machine-specific instruction sequences due to the Implementatio N and vendor dependency.

Casting Primitive Types

Primitive types is those non-composed types which can be handled directly by the (virtual) machine instructions, i.e., , long , float , etc ... Those types doesn ' t has inner structure, and is always passed by value if the programmer doesn ' t specify explicitly othe R behavior (using the out and ref modifiers). Let's see a simple example about using and casting primitive types:

Hide Copy Code
10;  3.4;  implicit conversion from int to double (1) z = (/// Explicit conversion from double to int (2) n = (//
                 
                   Explicit conversion from int. to UINT (3) 
                       

This sample performs some conversions in the set of primitive types, leaving in some cases the casting tasks to the Compil ER and marking conversions explicitly in some other cases.

OK, time to dive into the MSIL generated code and check the impact of type casts in our code:

Hide Copy Code
.Locals init ([0] int32 z, [1] float32 R, [2] unsigned int32 n) il_0000:Ldc.i4.sTen il_0002:Stloc.0 il_0003:LDC.R4 (9A9959il_0008):Stloc.1 il_0009:ldc.i4.s 20 il_000b: stloc.2 // (1) il_000c: ldloc. 0 IL_000d:conv.r4 il_000e: stloc. 1 il_000f: ldloc. 1 // (2) IL_0010:conv.i4 il_0011:  Stloc. 0 il_0012: ldloc. 0 // (3) il_0013: stloc.2 il_0014: ret        

As we can see, there was several Conv.XY instructions in the code, whose function was to convert the value at the top of the Stack to the type designed in the opcode (R4, I4, etc ...). From now, we know that the "innocent" explicit and implicit conversions between primitive types generate instructions whic H can is avoided with a consistent type usage. The same conversions is applied in 64-bit data types, such as double , long and ulong .

Note that the last type cast doesn ' t need a explicit " Conv " opcode due to the nature of the involved types: and int ; These types has a very close storage structure (big endian bit order with a sign bit in the signed type) and conversion s IGN issues must is controlled by the programmer.

A Special kind of primitive type bool is (handled internally as an int ), whose conversions to numeric types (and Backwa RD) is not allowed in C #, so we'll not study them.

Downcasting Object References

C # provides-ways for casting object references (note so all types, unless those studied in the previous section, is Reference types):

Hide Copy Code
New MyClass ();    //(1)    //(2) </CODE>   

The previous is a good example of downcasting (casting from the top to the bottom of the class hierarchy). The method used to perform the cast appears to is the same, but the generated MSIL sequences is a bit different:

Hide Copy Code
.Locals init ([0] Object MyClass) il_0000:newobj instance void Sample.myclass::.ctor () il_0005: stloc. 0 il_0006: ldloc. 0 // (1) il_0007: castclass Sample.myclass il_000c:callvirt instance void Sample.MyClass ::D osome () il_0011: ldloc. 0 // (2) il_0012: isinst Sample.myclass il_0017:callvirt instance void Sample.MyClass ::D osome () il_001c: ret         

In the first line of code, the compiler emits a " Castclass " opcode, which converts the reference to the type specified between The parenthesis if possible (if not, a InvalidCastException exception is thrown).

In the second case, the as operator is translated as a " IsInst " opcode, which works much faster, because it only checks The reference type but doesn ' t perform any sort of cast (nor throws any exception).

In performance terms, we prefer the second option, because the " IsInst " speeds up much more the code execution, avoiding Ty PE casts and exception throwing. Here are a sample of the speed increment obtained using the " as " "Operator:

In the other hand, parenthesized casts give a better error control to programmers, avoiding the Null-reference errors Obta ined when invalid typecasts happen using the " as " operator.

Upcasting Object References

Let's make the opposite! Now it's time for climbing the to the class hierarchy, and see how slow (or fast) is these sort of casts. The following example creates an object of the type and MyDerivedClass stores it reference in a MyClass type variable:

Hide Copy Code
New Myderivedclass ();    MyClass MyClass = Myderivedclass;

And the produced code is:

Hide Copy Code
. locals init ([0] class Sample.myderivedclass Myderivedclass, [1] class Sample.MyCla SS MyClass) il_0000: newobj instance void sample.myderivedclass::.ctor () il_0005: stloc.0 il_0006: ldloc. 0 il_0007: stloc. 1 il_0008: ret           

As we can see, there is no conversion opcodes, just reference loading and storing. This was good for out efficiency purposes ... as expected, upcasting type checks was made at compile time and the runtime Co STS is as cheap as a simple assign between variables of the same type.

Casting operators

C # language contains a great feature which allows to define implicit and explicit conversion operators. The efficiency of these casting methods depends on the casting method implementation. Anyway, these functions is always static and has only one parameter, so the procedure call overhead is small (no " this " parameter should be passed). Anyway, it seems to is that the Microsoft C # compiler doesn ' t inline those methods, so arranging parameters and return add Resses in the stack is slow your code execution speed.

Putting it all together

Here is some general tips for optimizing your programs based on the results obtained in the previous sections:

    • Numeric type conversions is usually expensive, take them off of the loops and recursive functions and use the same numeri C types when possible.
    • Downcasting is a great invention but the type checks involved has a great impact on execution performance, check the Obje CT types out of loops and recursive functions, and with the " as " operator into them.
    • Upcasting is cheap!, use it everywhere you need.
    • Build lightweight conversion operators to make custom casts faster.
Tools used

All the tests and disassemblies has been made using the tools included in the. NET Framework SDK. ILDasm can tell your much about your program's performance flaws, so play with it.

License

This article have no explicit license attached to it but could contain usage terms in the article text or the download files themselves. If in doubt, contact the author via the discussion board below.

A List of licenses authors might use can is found here

The cost of the "Go" C # type conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.