Some Thoughts on Level 3 events caused by a type conversion,

Source: Internet
Author: User

Some Thoughts on Level 3 events caused by a type conversion,

 

A third-level event occurred some time ago. It turned out that it was an endless loop caused by overflow. The event in the company was still a very risky thing. In addition to the large boss, it had to be deducted for money.

A reasonable explanation from the top management: If you work in a small company, it may be okay even if the website goes down for a day. If you lose money every second in a large company, the loss may be even

We won't be able to do it in Year 12, so the sense of responsibility and Code awareness are really important.

Let's take a look at the problem code. Here I made a little modification. The code is very simple, that is, to get the number of binary 1 in the num parameter.

 1         static void Run(long num) 2         { 3             int i = 1; 4  5             long num2 = 0; 6  7             List<int> list = new List<int>(); 8  9             while ((num2 = (long)Math.Pow(2, i - 1)) <= num)10             {11                 if ((num & num2) > 0)12                 {13                     list.Add(i);14                 }15                 i++;16             }17         }

If this is the code you wrote, can you see the problem at a glance? We know that long is 8 bytes, that is, 64-bit binary, and because the highest bit in the binary is the symbol bit, when

The minvalue of long is displayed when the power of 2 is 63. Therefore, when I = 64, the above Code is converted into long due to strong conversion, so the final result is changed to long MinValue, as shown in figure

If it is recycled, it will go further and further on the negative number road. Then the overflow of this range is not adopted by CLR, so it will not throw us an OverflowException. This is the tragedy.

The problem occurs relentlessly, but can you think about it? In the strong conversion of primitive types, it is really suitable for using (long), (int) is this strong conversion mode? From this example

We can see that this (long) mode does not detect overflow at all, so it is best not to use this mode in the future, because in. in the. net Framework, there are too many strong conversion methods.

I know that there is no overflow detection. Some people may think that the conversion speed is the fastest, but how many people can swear that my program will never overflow?

I am also fully responsible for any behavior exceptions caused by program overflow?

In order to promote the strong conversion of non (long), the following describes other strong conversion methods.

 

I. To better understand the code, Let's first look at the original non-detection mode.

1             long i = long.MaxValue;2             int j = (int)i;

In IL, we can be delighted to see that this strong conversion without detecting overflow also has the proprietary IL command: conv. i4, which means to convert the value at the top of the computing stack to int32.

 

Ii. checked

From the day we learned the C # language, we knew there was a checked. Its only role was to detect overflow. If yes, an exception is thrown. Let's look at it and the undetected

What are the differences between methods in IL.

1             long i = long.MaxValue;2 3             checked4             {5                 int j = (int)i;6             }

Good guy, it seems that a string of code is actually an instruction in IL, But there is actually an ovf. I think you should also be aware that there is an extra overflow detection during the conversion.

If you refute the performance, it is true that the performance of this command must be slower than that without detection. What I want to do on the web is slow and acceptable.

 

3. Convet. ToXXX.

This is the class C # used to encapsulate conversion operations for us. This is also highly recommended for my blog writing. Since it is recommended by me, it will certainly detect overflow. Next we will

Look at the code and IL.

1             long i = long.MaxValue;2 3             int j = Convert.ToInt32(i);

In IL, we can see that there are no special conversion commands, so the judgment must be in the Toint32 method. The following eyes will go to its source code to take a look.

From the source code, we find that the original code is so concise, especially this if. if ToIntXXX is used at the time, the event may be blocked in the test environment.

Day, this if is your last lifeline.

 

Iv. IConvertible Interface

Many types of conversion methods are encapsulated in this interface, and all primitive types are implemented, but it does not mean that Convert. ToXXX is called again...

1             long i = 1;2 3             int j = ((IConvertible)i).ToInt32(null);

From the above IL, we can see that there is actually a box, and it is no wonder that IConvertible is a reference type. How can it be left empty? This interface method is not worth mentioning in the value type conversion scenario.

It is inconvenient to mention, but there is also a large performance loss.

 

Well, the summative words are also coming.

① No-check code mode: This mode is not recommended. It will kill you one day.

② Checked: Although there is a check, it is difficult to write. Of course, you can also set global detection in.

③ Convert. Toxxx: This article was written to advocate it, so I won't talk about the importance. It will save you one day.

④ IConvertible: in value-type scenarios, the performance is the worst and coding is not good.

 




Related Article

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.