퍼포먼스를 고려한 자바 코딩
예제1)
package com.model;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(10)); // 랩퍼클래스인 Integer를 이용, 객체로 생성해서 배열에 넣는 기본방법
list.add(20); // 오토박싱으로 넣는 방법
list.add(30);
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
} // 메서드를 반복해서 호출하므로 메모리를 소모하여 퍼포먼스가 저하된다.
}
}
위의 예제를 다음과 같이 수정할 수 있다.
package com.model;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(10));
list.add(20);
list.add(30);
int count = list.size(); // 메서드를 한번만 호출
for(int i=0; i<count; i++) {
System.out.println(list.get(i));
} // 다음 이 호출한 메서드에서 데이터만 반복해서 읽어오므로 메서드를 반복해서 호출할 때보다 퍼포먼스가 향상된다.
}
}
반복문 안에서 메서드를 호출하면 퍼포먼스가 떨어진다.
메서드는 반복문 밖에서 호출한 뒤 반복문 안에서는 이미 메서드로 불러온 데이터를 읽기만 하도록 코딩한다.
예제2) 동일한 문자결합 기능을 메서드에 따른 퍼포먼스의 비교
package com.model;
public class Ex02 {
public static void main(String[] args) {
Ex02 ex = new Ex02();
for(int i=0; i<2 ; i++){
ex.stringArithTest();
ex.stringBufferTest();
ex.stringTest();
System.out.println();
}
}
private void stringTest(){
long start = System.currentTimeMillis();
String x = "";
for(int i=0; i < 10000; i++){
x = x.concat("abcdefghijklmnopq"); // concat 사용(퍼포먼스 나쁨)
}
System.out.println("x.length(): "+ x.length());
System.out.println("stringTest()->concat()메서드 이용: "
+ (System.currentTimeMillis()-start));
}
private void stringBufferTest(){
long start = System.currentTimeMillis();
StringBuffer x = new StringBuffer();
for(int i=0; i < 10000; i++){
x = x.append("abcdefghijklmnopq"); // append 사용(퍼포먼스 가장 좋음!)
}
System.out.println("x.length(): "+ x.length());
System.out.println("stringBufferTest()->append()메서드 이용: "
+ (System.currentTimeMillis()-start));
}
private void stringArithTest(){
long start = System.currentTimeMillis();
String x = "";
for(int i=0; i < 10000; i++){
x += "abcdefghijklmnopq"; // += 연산자 사용(퍼포먼스 가장 나쁨!!)
}
System.out.println("x.length(): "+ x.length());
System.out.println("stringArithTest()->연산자 이용: "
+ (System.currentTimeMillis()-start));
}
}
결과)
x.length(): 170000
stringTest()->concat()메서드 이용: 329
x.length(): 170000
stringArithTest()->연산자 이용: 891
x.length(): 170000
stringBufferTest()->append()메서드 이용: 1
x.length(): 170000
stringTest()->concat()메서드 이용: 220
※ concat은 문자열을 붙일 때마다 메모리가 할당되어 기존에 사용한 메모리가 남아있어 효율이 나쁘다.
메모리 사용이 종료되었다고 가비지 컬렉션이 바로 삭제해주지는 않기 때문. (연산자는 효율이 이보다도 더 나쁘다)
StringBuffer, StringBuilder는 가변 메모리를 기본으로 갖추고 있다.
문자열 붙이기는 반드시 StringBuffer, StringBuilder 클래스의 append 사용!!
'자바의 기초문법' 카테고리의 다른 글
NIO의 Path, URI, Files 클래스 (0) | 2016.05.19 |
---|---|
자바의 Varargs (가변인자) (0) | 2016.05.19 |
람다 표현식 (Lambda Expression) (0) | 2016.05.18 |
import static (0) | 2016.05.18 |
싱글톤 패턴 (0) | 2016.05.18 |