싱글톤과 프로토타입 객체에 대한 성능 비교를 위해 아래와 같이 테스트 코드를 작성하였다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigDecimal; | |
public class SingletonObjectPerformanceTest { | |
public static void main(String[] args) throws InterruptedException { | |
final Singleton singleton = new Singleton(); | |
long startTime = System.currentTimeMillis(); | |
for (int i = 0; i < 800000; i++) { | |
Thread t = new Thread() { | |
@Override | |
public void run() { | |
callPrototype(); | |
}; | |
// call 싱글톤 | |
public void callSingleton() { | |
singleton.test(); | |
} | |
// call prototype | |
public void callPrototype() { | |
Prototype prototype = new Prototype(); | |
prototype.test(); | |
} | |
}; | |
t.start(); | |
t.join(); | |
} | |
long endTime = System.currentTimeMillis(); | |
double completeTime = endTime - startTime; | |
BigDecimal resuleTime = new BigDecimal(completeTime).divide(new BigDecimal(1000)); | |
System.out.println("complete time : " + resuleTime.toString() + "초"); | |
} | |
} | |
class Singleton { | |
public void test() { | |
System.out.println("singleton!!"); | |
} | |
} | |
class Prototype { | |
public void test() { | |
System.out.println("prototype!!"); | |
} | |
} |
싱글톤은 객체 한 개만 생성한 후 그 안에 있는 test() 메소드를 호출하였고, 프로토타입은 매번 객체를 생성한 후 test() 메소드를 실행하였다.
헌데 테스트 결과가 이상하다.
쓰레드 count |
싱글톤 |
프로토타입 |
10,000 |
1.651초 |
1.594초 |
20,000 |
3.158초 |
3.306초 |
30,000 |
4.59초 |
4.978초 |
40,000 |
6.545초 |
6.261초 |
50,000 |
8.41초 |
7.81초 |
60,000 |
9.456초 |
9.65초 |
70,000 |
10.617초 |
11.552초 |
80,000 |
12.78초 |
12.752초 |
90,000 |
14.952초 |
14.354초 |
100,000 |
16.184초 |
15.169초 |
1,000,000 |
218.941초 |
174.753초 |
분명 매번 객체를 생성하는 프로토타입을 이용한 테스트가 싱글톤 테스트보다 성능이 안 좋아야 한다.
하지만 테스트 결과는 그 반대를 보여주고 있다.
같은 테스트를 여러번 해도 수행 시간(초)의 미미한 차이만 있었지 결국 프로토타입 테스트가 대부분 싱글톤보다 빨랐다.
로컬 테스트 환경이라서 그런 걸까?
아니면 내가 알지 못하는 어떤 원인이? (아시는 분 댓글 좀 부탁 드립니다.)
여하튼 객체 생성 성능 비교를 해보니 싱글톤으로 설계를 하던 프로토타입으로 설계를 하던 큰 성능 차이는 없는 것 같다.
'프로그래밍' 카테고리의 다른 글
스프링 interceptor afterCompletion 메소드 이용 시 참고할 사항 (0) | 2013.02.26 |
---|---|
스프링 CGLib 클래스 프록시 사용 (0) | 2013.02.26 |
spring MVC 404 처리 방법? (3) | 2013.02.26 |
개방 폐쇄 원칙 OCP (Open-Closed Principle) (2) | 2013.02.26 |
리눅스에서 java main 실행 (0) | 2013.02.14 |
ajax HTTP, HTTPS에 따른 크로스 도메인 문제 (3) | 2013.02.05 |
@Scheduled expression 시간 설정을 properties로 빼는 방법 (3) | 2013.01.29 |
공통 상수를 인터페이스에 정의하는 이유는 뭘까? (3) | 2013.01.29 |