반응형
#1. if-else 샘플 코드
배송방법과 수하물의 무게에 따라 요금을 계산하는 아래와 같은 코드를 샘플로 작성합니다.
public static double calculateShippingCost(String shippingType, double weight) {
if (shippingType.equals("STANDARD")) {
return weight * 5.0;
} else if (shippingType.equals("EXPRESS")) {
return weight * 10.0;
} else if (shippingType.equals("SAME_DAY")) {
return weight * 20.0;
} else if (shippingType.equals("INTERNATIONAL")) {
return weight * 50.0;
} else if (shippingType.equals("OVERNIGHT")) {
return weight * 30.0;
}
return 0;
}
#2. switch & Pattern Matching(JDK21)
swich 구문과 JDK21 이상에서 사용 가능한 Pattern Matching 을 사용하여 작성합니다.
public static double calculateShippingCost2(String shippingType, double weight) {
return switch (shippingType) {
case null -> throw new IllegalArgumentException();
case "STANDARD" -> weight * 5.0;
case "EXPRESS" -> weight * 10.0;
case "SAME_DAY" -> weight * 20.0;
case "INTERNATIONAL" -> weight * 50.0;
case "OVERNIGHT" -> weight * 30.0;
default -> 0;
};
}
#3. enum & hashmap
enum 을 이용한 코드도 작성합니다.
public static double calculateShippingCost3(String shippingType, double weight) {
return ShippingEnum.getShppingCost(shippingType, weight);
}
@Getter
public enum ShippingEnum {
STANDARD(5.0),
EXPRESS(10.0),
SAME_DAY(20.0),
INTERNATIONAL(50.0),
OVERNIGHT(30.0);
private static final Map<String, ShippingEnum> lookup =
Collections.unmodifiableMap(Stream.of(values())
.collect(Collectors.toMap(ShippingEnum::name, Function.identity())));
private final double cost;
ShippingEnum(double cost) {
this.cost = cost;
}
public static double getShppingCost(String shippingType, double weight) {
return lookup.get(shippingType).getCost() * weight;
}
}
#4. 성능 측정
각각 1억번씩 반복하여 시간을 측정해봅시다.
@GetMapping("/test")
public void CalcTest(String[] args) {
String[] shippingType = new String[] {"STANDARD", "EXPRESS", "SAME_DAY", "INTERNATIONAL", "OVERNIGHT"};
StopWatch stopWatch = new StopWatch("if-else vs switch");
stopWatch.start("if-else");
for (int i = 0; i < 100000000; i++) {
double random = Math.random() * 5;
int idx = (int) random;
calculateShippingCost(shippingType[idx], random);
}
stopWatch.stop();
stopWatch.start("switch");
for (int i = 0; i < 100000000; i++) {
double random = Math.random() * 5;
int idx = (int) random;
calculateShippingCost2(shippingType[idx], random);
}
stopWatch.stop();
stopWatch.start("enum map");
for (int i = 0; i < 100000000; i++) {
double random = Math.random() * 5;
int idx = (int) random;
calculateShippingCost3(shippingType[idx], random);
}
stopWatch.stop();
log.info(stopWatch.prettyPrint());
}
#5. 결과
enum > if-else > switch 순으로 빠른것을 확인할 수 있습니다.
결과적으로, 속도차이가 다이나믹하게 나는 것 같지는 않으니
코드 가시성, enum 필요성 등등을 종합적으로 고려하여 그때그때 다르게 적용하면 될 것 같습니다.
fin.
반응형
'Java' 카테고리의 다른 글
예제로 알아보는 Java Stream API (0) | 2025.02.07 |
---|---|
[List] ArrayList 와 LinkedList (0) | 2021.03.18 |
댓글