Which efficiency is fast in Java if and switch

Source: Internet
Author: User

The first thing to look at is that if the application scope is wide, as long as the Boolean expression can be judged by the IF, and switch can only make a numeric comparison of the base type. The comparability of the two is limited to the comparison of two basic types.
When it comes to numerical comparisons of basic types, of course there are two numbers. And then the point is--
Each sentence of the IF statement is independent, see the following statement:
if (a = = 1) ...
else if (a = = 2) ...
So that a is read into the register two times, 1 and 2 are read into the register one at a time. So did you find that actually a read two times is a bit redundant, you only need to read the register one time before all the comparison is complete, the rest is the extra cost. But the IF statement has to take the two numbers out of memory each time to read the registers, it does not know that you are actually comparing the same a.
So switch case comes out and changes the above into a switch case version:
Switch (a) {
Case 0:
Break
Case 1:
}

Because of the specific rules, he knew from the beginning that you were going to be better than a, so a one-time read, compared to if save a lot of overhead.

Then the switch statement hits the third option with the same time as the If/else if statement hits the third option, based on a large number of actual program tests (regardless of the difference in compiler optimizations, assuming the best optimizations).
Hit the speed of the first, second option if statement fast, hitting the fourth and after the speed of the option switch statement fast.

So, if all options appear to have the same probability, the conclusion is that the switch and If/else if the 5 options (including default) are the same. Less than 5 options if fast, above 5 for option switch FAST!

Which efficiency is fast in Java if and switch

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.