Reflection 호출의 성능 저하 테스트

2011. 4. 12. 10:28Java


심심해서 해봤습니다.

결론은 함수 호출을 비교했을때 30배 이상 차이 납니다.

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AnnotationTest {
private long start;
private long end;
public AnnotationTest(){
}
public void callGeneral(){
}
@AnoTest
public void callAnnotation(){
}
public void start(){
start = System.currentTimeMillis();
}
public void end(String tag){
end = System.currentTimeMillis();
System.out.println(tag+" 걸린시간="+(end-start)+"ms");
}
/**
* @param args
* @throws InvocationTargetException 
* @throws IllegalAccessException 
* @throws IllegalArgumentException 
* @throws ClassNotFoundException 
* @throws InstantiationException 
*/
public static void main(String[] args) throws Exception {
int max=1000000;
int i =0;
AnnotationTest test = new AnnotationTest();
test.start();
for(i=0;i<max;i++){
test.callGeneral();
}
test.end("일반 메소드 호출");
Class c = Class.forName("com.rontab.jboss.AnnotationTest");
Method[] ms = c.getDeclaredMethods();
Method callAnoMethod=null;
for(Method m:ms){
Annotation[] ans = m.getAnnotations();
System.out.println("method="+m.getName()+" ans="+ans);
for(Annotation a:ans){
System.out.println("=>"+a.annotationType());
if(a.annotationType()==AnoTest.class){
callAnoMethod = m;
break;
}
}
}
System.out.println(callAnoMethod.getName()+" Method founded.");
test.start();
Object ins = c.newInstance();
for(i=0;i<max;i++){
callAnoMethod.invoke(ins,null);
}
test.end("anotation 메소드 호출");
}

}



import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AnoTest {
}