Let us consider the performance of string switches. Here we have two methods, both of which return the same values.
import java.util.HashMap;
public class Program {
static boolean isMoth(String value) {
switch (value) {
case
"Atlas Moth":
case
"Beet Armyworm":
case
"Indian Meal Moth":
case
"Ash Pug":
case
"Latticed Heath":
case
"Ribald Wave":
case
"The Streak":
return true;
default:
return false;
}
}
static boolean isMothOr(String value) {
return value ==
"Atlas Moth" || value ==
"Beet Armyworm"
|| value ==
"Indian Meal Moth" || value ==
"Ash Pug"
|| value ==
"Latticed Heath" || value ==
"Ribald Wave"
|| value ==
"The Streak";
}
public static void main(String[] args) throws Exception {
// Initialize HashMap.
HashMap<String, Boolean> hash = new HashMap<>();
hash.put(
"Atlas Moth", true);
hash.put(
"Beet Armyworm", true);
hash.put(
"Indian Meal Moth", true);
hash.put(
"Ash Pug", true);
hash.put(
"Latticed Heath", true);
hash.put(
"Ribald Wave", true);
hash.put(
"The Streak", true);
String[] tests = {
"Ribald Wave",
"Java",
"Beet Armyworm",
"Python" };
int max = 100000000;
long t1 = System.currentTimeMillis();
// Version 1: switch.
for (int i = 0; i < max; i++) {
int count = 0;
for (String test : tests) {
if (isMoth(test)) {
count++;
}
}
if (count != 2) {
throw new Exception();
}
}
long t2 = System.currentTimeMillis();
// Version 2: or-expression.
for (int i = 0; i < max; i++) {
int count = 0;
for (String test : tests) {
if (isMothOr(test)) {
count++;
}
}
if (count != 2) {
throw new Exception();
}
}
long t3 = System.currentTimeMillis();
// Version 3: use HashMap.
for (int i = 0; i < max; i++) {
int count = 0;
for (String test : tests) {
if (hash.containsKey(test)) {
count++;
}
}
if (count != 2) {
throw new Exception();
}
}
long t4 = System.currentTimeMillis();
// Results.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
System.out.println(t4 - t3);
}
}
1236 ms Switch
801 ms Or
2147 ms HashMap