#10 effective java: item 6

This commit is contained in:
haerong22
2022-05-23 02:25:56 +09:00
parent 69ddddd1ce
commit 75848752a2
3 changed files with 68 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
package com.example.effectivejava.chapter01.item06;
import java.util.regex.Pattern;
// 값비싼 객체를 재사용해 성능을 개선한다. (32쪽)
public class RomanNumerals {
// 코드 6-1 성능을 훨씬 더 끌어올릴 수 있다!
static boolean isRomanNumeralSlow(String s) {
return s.matches("^(?=.)M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");
}
// 코드 6-2 값비싼 객체를 재사용해 성능을 개선한다.
private static final Pattern ROMAN = Pattern.compile(
"^(?=.)M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$");
static boolean isRomanNumeralFast(String s) {
return ROMAN.matcher(s).matches();
}
public static void main(String[] args) {
boolean result = false;
long start = System.nanoTime();
for (int j = 0; j < 100; j++) {
//TODO 성능 차이를 확인하려면 xxxSlow 메서드를 xxxFast 메서드로 바꿔 실행해보자.
result = isRomanNumeralSlow("MCMLXXVI");
}
long end = System.nanoTime();
System.out.println(end - start);
System.out.println(result);
}
}

View File

@@ -0,0 +1,18 @@
package com.example.effectivejava.chapter01.item06;
public class Strings {
public static void main(String[] args) {
String hello = "hello";
//TODO 이 방법은 권장하지 않습니다.
String hello2 = new String("hello");
String hello3 = "hello";
System.out.println(hello == hello2);
System.out.println(hello.equals(hello2));
System.out.println(hello == hello3);
System.out.println(hello.equals(hello3));
}
}

View File

@@ -0,0 +1,19 @@
package com.example.effectivejava.chapter01.item06;
public class Sum {
private static long sum() {
// TODO Long을 long으로 변경하여 실행해 보세요.
Long sum = 0L;
for (long i = 0; i <= Integer.MAX_VALUE; i++)
sum += i;
return sum;
}
public static void main(String[] args) {
long start = System.nanoTime();
long x = sum();
long end = System.nanoTime();
System.out.println((end - start) / 1_000_000. + " ms.");
System.out.println(x);
}
}