其他类
public abstract class ProductAbstract {
public void test() {
System.out.println("--------------test----");
}
}
public class ProductA extends ProductAbstract{
}
public class ProductB extends ProductAbstract{
}
测试反射创建实例耗时
package com.xy.designmode.factory;
import com.xy.util.TimeUtil;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class TestFactory {
private static Map<String, String> map = new HashMap<>();
private static Map<String, Class<?>> classCache = new HashMap<>();
static {
map.put("productA", "com.xy.designmode.factory.ProductA");
map.put("productB", "com.xy.designmode.factory.Productb");
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
TimeUtil.time("ALL");
testClassForNameUseTime();
TimeUtil.time("ALL");
}
private static void testClassForNameUseTime() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
TimeUtil.time();
String objKey = "productA";
String clazz = map.get(objKey);
Class<?> aClass = null;
for (int i = 0; i < 100000; i++) {
aClass = Class.forName(clazz);
}
TimeUtil.time();
for (int i = 0; i < 100000; i++) {
aClass.getConstructor().newInstance();
}
TimeUtil.time();
}
}
testClassForNameUseTime()
间隔:235毫秒 --- Class.forName
间隔:26毫秒 --newInstance
结论: Class.forName耗时远大于 newInstance
改进: class放入缓存
import com.xy.util.TimeUtil;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class TestFactory {
private static Map<String, String> map = new HashMap<>();
private static Map<String, Class<?>> classCache = new HashMap<>();
static {
map.put("productA", "com.xy.designmode.factory.ProductA");
map.put("productB", "com.xy.designmode.factory.Productb");
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
TimeUtil.time("ALL");
testClassForNameUseTime2();
TimeUtil.time("ALL");
}
private static void testClassForNameUseTime2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
TimeUtil.time();
String objKey = "productA";
String clazz = map.get(objKey);
Class<?> aClass = null;
for (int i = 0; i < 100000; i++) {
aClass = classCache.get(objKey);
if(aClass == null){
aClass = Class.forName(clazz);
classCache.put(objKey,aClass);
}
}
TimeUtil.time();
for (int i = 0; i < 100000; i++) {
aClass.getConstructor().newInstance();
}
TimeUtil.time();
}
}