Is and as performance differences in type conversion

Source: Internet
Author: User
Is and as are common operations in. net. Both of them can implement type-safe conversion, but they are different.

For example

Public class employee {} public void add (Object OBJ) // write method 1 {employee e = NULL; If (obj is employee) {e = (employee) OBJ; // normal processing} else {// other processing} public void add (Object OBJ) // write method 2 {employee e = OBJ as employee; If (OBJ = NULL) {// other processing} else {// normal processing }}

In the above Code, obj is converted to employee, both of which are OK in writing and can be compiled and run. However, the two have some differences in performance.
The is operation needs to determine whether the OBJ type is employee. If yes, it will be forcibly converted to E = (employee) obj. During forced conversion, CLR will judge the type of OBJ again. If it is not of the employee type,
System. invalidcastexception is thrown.
The as operator performs a type judgment in the CLR stage. If it is an employee, it is converted to the employee type. If not, it is converted to null. Therefore, we can determine if (OBJ = NULL) in the second method.
I believe that I have understood the performance differences between the two methods. The expression of IS requires two type judgments, and as only requires one type judgment.
Of course, some programmers directly adopt the following method:

Public void add (Object OBJ) // write method 3 {try {employee e = (employee) OBJ; // normal processing} catch {// other processing throw ;}}

Statement 3 is feasible in the program, but it is not recommended to use try-catch to catch exceptions that fail to force conversion, which has a greater impact on performance.
The fourth edition of CLR via C # is more inclined to write 2.

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.