Skip to content

Instantly share code, notes, and snippets.

@stephenh
Created July 18, 2009 00:59
Show Gist options
  • Save stephenh/149365 to your computer and use it in GitHub Desktop.
Save stephenh/149365 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
public class MapTest2 extends TestCase {
private static final FilterImpl staticFilter = new FilterImpl();
public void testFoo() {
List<Integer> list = this.makeList();
Assert.assertEquals(4, list.size());
long staticTime = 0;
long instanceTime = 0;
long inlineTime = 0;
for (int j = 0; j < 100; j++) {
long a = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
doStatic(list);
}
long b = System.nanoTime();
staticTime += (b - a);
long c = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
doNonStatic(list);
}
long d = System.nanoTime();
instanceTime += (d - c);
long e = System.nanoTime();
for (int i = 0; i < 1000000; i++) {
doInline(list);
}
long f = System.nanoTime();
inlineTime += (f - e);
}
System.out.println("static: " + staticTime);
System.out.println("instan: " + instanceTime);
System.out.println("inline: " + inlineTime);
}
private void doInline(List<Integer> list) {
List<Integer> list2 = new ArrayList<Integer>();
for (Integer i : list) {
if (i.intValue() == 3) {
list2.add(i);
}
}
Assert.assertEquals(1, list2.size());
}
private void doStatic(List<Integer> list) {
List<Integer> list2 = filter(list, staticFilter);
Assert.assertEquals(1, list2.size());
}
private void doNonStatic(List<Integer> list) {
List<Integer> list2 = filter(list, new FilterImpl());
Assert.assertEquals(1, list2.size());
}
private List<Integer> makeList() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
return list;
}
public interface Filter {
boolean filter(Integer i);
}
public List<Integer> filter(List<Integer> list, Filter filter) {
List<Integer> list2 = new ArrayList<Integer>();
for (Integer i : list) {
if (filter.filter(i)) {
list2.add(i);
}
}
return list2;
}
public static class FilterImpl implements Filter {
public boolean filter(Integer i) {
return i.intValue() == 3;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment