Permalink
Browse files

test reflection performance

  • Loading branch information...
1 parent adb479b commit ebf83ebd27205bc6f704b4a00d7353bce677c3fe feng committed Mar 7, 2011
@@ -1,4 +1,4 @@
-package jcip;
+package lang;
import java.util.Random;
import java.util.concurrent.ConcurrentMap;
@@ -32,26 +32,26 @@ public MyValue() {
}
}
+ // use jconsole. No OutOfMemoryError!
@Test
public void testCache() {
ConcurrentMap<Object, Object> map = new MapMaker().softKeys()
.softValues().makeMap();
- for (int i = 0; i < 10; i++) {
- map.put(1, 1);
-
- System.out.println(map);
- }
-
-//
-// for (;;) {
-// map.put(new MyKey(), new MyValue());
-//// map.get
-// try {
-// TimeUnit.MILLISECONDS.sleep(r.nextInt(10));
-// } catch (InterruptedException ignore) {
-// }
+// for (int i = 0; i < 10; i++) {
+// map.put(1, 1);
+//
+// System.out.println(map);
// }
+ for (;;) {
+ map.put(new MyKey(), new MyValue());
+ // map.get
+ try {
+ TimeUnit.MILLISECONDS.sleep(r.nextInt(10));
+ } catch (InterruptedException ignore) {
+ }
+ }
+
}
}
@@ -1,4 +1,4 @@
-package jcip;
+package lang;
import org.junit.Assert;
import org.junit.Test;
@@ -0,0 +1,54 @@
+package lang;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Random;
+
+import org.junit.Test;
+
+public class ReflectionPerformance {
+
+ private static final String[] strs;
+
+ static {
+ final String alpha = "abcdefghijklmnopqrstuvwxyz";
+ final Random r = new Random();
+ final int count = 1000 * 10000;
+ strs = new String[count];
+ for (int i = 0; i < count; i++) {
+ final int size = r.nextInt(10);
+ StringBuilder sb = new StringBuilder(size);
+ for (int j = 0; j < size; j++) {
+ sb.append(alpha.charAt(r.nextInt(alpha.length())));
+ }
+ strs[i] = sb.toString();
+ }
+
+ }
+
+ // 2011/3/7 reflection is about 10/1 the speed of normal call. 9.042s<->0.849s
+
+ @Test
+ public void testReflectionTime() throws SecurityException,
+ NoSuchMethodException, IllegalArgumentException,
+ IllegalAccessException, InvocationTargetException {
+ Method length = String.class.getMethod("length", null);
+ Method toUpperCase = String.class.getMethod("toUpperCase", null);
+
+ for (int i = 0; i < strs.length; i++) {
+ int l = (Integer) length.invoke(strs[i], null);
+ String up = (String) toUpperCase.invoke(strs[i], null);
+ }
+ }
+
+ @Test
+ public void testNoReflectionTime() throws SecurityException,
+ NoSuchMethodException, IllegalArgumentException,
+ IllegalAccessException, InvocationTargetException {
+ for (int i = 0; i < strs.length; i++) {
+ int length = strs[i].length();
+ String upperCase = strs[i].toUpperCase();
+ }
+ }
+
+}

0 comments on commit ebf83eb

Please sign in to comment.