Created
November 21, 2014 17:15
-
-
Save mikeholler/ea0f786b24175f9b9eba to your computer and use it in GitHub Desktop.
Profiling String Comparison vs. Class.isAssignableFrom(...) Comparison.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String comparison: 5 ms | |
Class comparison with isAssignableFrom: 1052 ms |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collection; | |
import java.util.List; | |
import java.util.Scanner; | |
public final class Scratch { | |
public static final String CORRECT_CLASS_NAME = List.class.getCanonicalName(); | |
public static final String INCORRECT_CLASS_NAME = Scanner.class.getCanonicalName(); | |
public static final int TIMES = 1000000; | |
public static long profileStringComp() { | |
final long startMillis = System.currentTimeMillis(); | |
for (int i = 0; i < TIMES; i++) { | |
CORRECT_CLASS_NAME.equals(CORRECT_CLASS_NAME); | |
INCORRECT_CLASS_NAME.equals(CORRECT_CLASS_NAME); | |
} | |
return System.currentTimeMillis() - startMillis; | |
} | |
public static long profileAssignableFromComp() throws ClassNotFoundException { | |
final long startMillis = System.currentTimeMillis(); | |
for (int i = 0; i < TIMES; i++) { | |
Collection.class.isAssignableFrom(Class.forName(CORRECT_CLASS_NAME)); | |
Collection.class.isAssignableFrom(Class.forName(INCORRECT_CLASS_NAME)); | |
} | |
return System.currentTimeMillis() - startMillis; | |
} | |
public static void main(final String[] args) throws Exception { | |
System.out.printf("String comparison: %d ms\n", profileStringComp()); | |
System.out.printf("Class comparison with isAssignableFrom: %d ms\n", | |
profileAssignableFromComp()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment