Skip to content

Instantly share code, notes, and snippets.

@gerner
Created April 13, 2011 22:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerner/918549 to your computer and use it in GitHub Desktop.
Save gerner/918549 to your computer and use it in GitHub Desktop.
how expensive are exceptions in java? why should they be exceptional?
import java.util.List;
import java.util.ArrayList;
public class Test {
public static void main(String [] args) {
int numIterations = Integer.parseInt(args[0]);
int totalS = Integer.parseInt(args[1]);
int numFoo = Integer.parseInt(args[2]);
//String [] s = { "not foo", "foo", "foo", "not foo", "more not foo", "long string that is most definitely not foo", "short", "more strings", "foo", "foo", "there's a lot of foo here", "foo", "foo", "foo"};
//String [] initialS = { "not foo", "not foo", "more not foo", "long string that is most definitely not foo", "short", "more strings", "there's a lot of foo here", "eight", "nine", "ten" };
List<String> listOfStrings = new ArrayList<String>();
for(int i=0; i < totalS - numFoo; i++) {
listOfStrings.add("not foo");
}
for(int i=0; i<numFoo; i++) {
listOfStrings.add("foo");
}
String[] s = new String[listOfStrings.size()];
s = listOfStrings.toArray(s);
long start = System.currentTimeMillis();
for(int i=0; i < Integer.parseInt(args[0]); i++) {
testExceptions(s);
}
System.out.println("exceptions took " + (System.currentTimeMillis() - start) + " for "+(totalS*numIterations)+" iterations");
start = System.currentTimeMillis();
for(int i=0; i < Integer.parseInt(args[0]); i++) {
testControlStructures(s);
}
System.out.println("constrol structures took " + (System.currentTimeMillis() - start) + " for "+(totalS*numIterations)+" iterations");
}
private static void testExceptions(String [] s) {
int totalLength = 0;
for (int i=0; i < s.length; i++) {
try {
totalLength += processString(s[i]);
} catch (IllegalArgumentException e) {
//no-op
}
}
}
private static void testControlStructures(String [] s) {
int totalLength = 0;
for (int i=0; i < s.length; i++) {
if(null != s && !("foo".equals(s[i]))) {
totalLength += processString(s[i]);
}
}
}
private static int processString(String s) {
if (null == s) {
throw new IllegalArgumentException("null is not allowed!");
}
if ("foo".equals(s)) {
throw new IllegalArgumentException("foo is not allowed!");
}
return s.length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment