Access over 20 million homework & study documents
search

Convert the switch statement in the second question to an if statemen

Content type

User Generated

Rating

Showing Page:
1/3
Convert the switch statement in the second question to an
if statement with multiple alternatives.
Solution
Switch sometimes has clear performance advantages over
an if-statement. Consider this example. The values 0
through 4 are tested many times.
Usually no cases in the switch or the if-statement are
matched. So the switch statement is executed faster.
Switch can slow down a method. If one case is most
common, checking it first in an if-statement is worth trying.
Java that times switch, if-statement
public class Program {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
// ... Use switch
int total = 0;
for (int i = 0; i < 100000000; i++) {
switch (i) {
case 0:
total--;
break;

Sign up to view the full document!

lock_open Sign Up
Showing Page:
2/3
case 1:
total -= 2;
break;
case 2:
case 3:
case 4:
total++;
break;
}
}
long t2 = System.currentTimeMillis();
// ... Use if-else
int total2 = 0;
for (int i = 0; i < 100000000; i++) {
if (i == 0) {
total2--;
} else if (i == 1) {
total2 -= 2;
} else if (i >= 2 && i <= 4) {
total2++;
}
}
long t3 = System.currentTimeMillis();
// ... Times
System.out.println(t2 - t1);

Sign up to view the full document!

lock_open Sign Up
Showing Page:
3/3

Sign up to view the full document!

lock_open Sign Up

Unformatted Attachment Preview

Convert the switch statement in the second question to an if statement with multiple alternatives. Solution Switch sometimes has clear performance advantages over an if-statement. Consider this example. The values 0 through 4 are tested many times. Usually no cases in the switch or the if -statement are matched. So the switch statement is executed faster. Switch can slow down a method. If one case is most common, checking it first in an if -statement is worth trying. Java that times switch, if-statement public class Program { public static void main(String[] args) { long t1 = System.currentTimeMillis(); // ... Use switch int total = 0; for (int i = 0; i < 100000000; i++) { switch (i) { case 0: total--; break; case 1: total -= 2; break; case 2: case 3: case 4: total++; break; } } long t2 = System.currentTimeMillis(); // ... Use if-else int total2 = 0; for (int i = 0; i < 100000000; i+ ...
Purchase document to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Anonymous
Really helpful material, saved me a great deal of time.

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4