return 문은 메서드를 호출하면 return문이 코드에 직접적으로 작성되어 있지 않을 경우 컴파일러가 추가하는데, 실제 구현코드는 동일하게는 작성할 수 없으므로, 기능적으로는 같은 동작이나, 처리방식이 약간 다르다.
public class returnvalue {
int add (int a, int b) {
return a+b;
}
}
public class returnvalue2 {
int add(int a, int b) {
int sum_result = a+b;
return sum_result;
}
}
맨아래 코드는 return 문을 활용한 예시이고, 맨위의 코드는 return문 없이 바로 계산값을 return하게 한 코드이다. 실제 바이트 코드를 들여다보면 동작이 약간 다르다.
계산값을 바로 return 하도록 작성된 소스의 바이트 코드
public returnvalue();
0 aload_0 [this]
1 invokespecial java.lang.Object() [8]
4 return
Line numbers:
[pc: 0, line: 3]
Local variable table:
[pc: 0, pc: 5] local: this index: 0 type: ch06.ex06.returnvalue
// Method descriptor #15 (II)I
// Stack: 2, Locals: 3
int add(int a, int b);
0 iload_1 [a]
1 iload_2 [b]
2 iadd
3 ireturn
Line numbers:
[pc: 0, line: 6]
Local variable table:
[pc: 0, pc: 4] local: this index: 0 type: ch06.ex06.returnvalue
[pc: 0, pc: 4] local: a index: 1 type: int
[pc: 0, pc: 4] local: b index: 2 type: int
}
return sum_result로 값을 반환하는 소스로 작성된 바이트 코드
public returnvalue2();
0 aload_0 [this]
1 invokespecial java.lang.Object() [8]
4 return
Line numbers:
[pc: 0, line: 3]
Local variable table:
[pc: 0, pc: 5] local: this index: 0 type: ch06.ex06.returnvalue2
// Method descriptor #15 (II)I
// Stack: 2, Locals: 4
int add(int a, int b);
0 iload_1 [a]
1 iload_2 [b]
2 iadd
3 istore_3 [sum_result]
4 iload_3 [sum_result]
5 ireturn
Line numbers:
[pc: 0, line: 5]
[pc: 4, line: 6]
Local variable table:
[pc: 0, pc: 6] local: this index: 0 type: ch06.ex06.returnvalue2
[pc: 0, pc: 6] local: a index: 1 type: int
[pc: 0, pc: 6] local: b index: 2 type: int
[pc: 4, pc: 6] local: sum_result index: 3 type: int
}
바이트코드를 살펴보면 리턴값을 넣는 코드가 추가되어 있다는것을 istore, iload가 추가되어 있어서 sum_result에 값을 넣는 작업이 추가적으로 이루어져 있다는 것을 알 수 있다.
다르다는것은 알겠는데 실제 대규모 처리시에 어떤 차이점이 있는지는 나중에 알아봐야 할것 같다.
'프로그래밍 > JAVA' 카테고리의 다른 글
[JAVA] static 변수에 관한 의문점 (0) | 2021.07.19 |
---|---|
[JAVA] 배열 array의 특성에 대하여 (0) | 2021.07.17 |
[JAVA] 자바의 변수 선언 특이성 static이 있고 없고 차이 (0) | 2021.06.30 |
[JAVA] 리터럴 상수중 String의 특징(equals사용) (0) | 2021.06.27 |
[JAVA] 리터럴literal (상수)에 대하여 (0) | 2021.06.26 |