JVM/JAVA
[JAVA] 클래스 변수를 잘 활용하라!(불필요한 객체 생성을 피하라)
글을 쓰는 개발자
2021. 11. 19. 20:52
반응형
1. 기본지식
- 클래스변수: 클래스가 메모리에 로딩(loading) 될 때 생성되어 프로그램이 종료될 때 까지 유지되며, public을 앞에 붙이면 같은 프로그래 내에서 어디서나 접근할 수 있는 전역변수의 성격을 갖는다.
- 지역변수: 메서드 내에 선언되어 메서드 내에서만 사용 가능하며, 메서드가 종료되면 소멸되어 사용할 수 없게 된다.
1. 클래스 변수를 활용한 케이스
public class StaticClass {
private static final Pattern PATTERN = Pattern.compile("^(?=.*[0-9])(?=.*[a-z])(?=.*[!@#$%^&+=])(?=\\S+$).{8,}$");
public static boolean validPassword(String password){
return PATTERN.matcher(password).matches();
}
}
2. 지역변수를 활용한 케이스
public class CompClass {
public static boolean validPassword(String password){
Pattern PATTERN = Pattern.compile("^(?=.*[0-9])(?=.*[a-z])(?=.*[!@#$%^&+=])(?=\\S+$).{8,}$");
return PATTERN.matcher(password).matches();
}
}
class SimpleTest {
@Test
void test_static(){
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String password = new String("Test12$@d");
StaticClass.validPassword(password);
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
@Test
void test_static2(){
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String password = new String("Test12$@d");
CompClass.validPassword(password);
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
}

반응형