Local variables: programming practice

To use the following methods:

public int methodOne() { int total = local_int_one + local_int_two; return total; } public int methodTwo() { return local_int_one + local_int_two; } 

1) Is the only difference in the above readability methods or is there a β€œbenefit” of micro-optimization in the Two () method?

2) Should the definition of local variables in a narrow space be avoided and avoided when possible? (I see that a method becomes unreadable if several calculations have to be performed in one expression)

+5
source share
1 answer

Short answer: methodTwo() bit more efficient.

methodOne() results in the following bytecode:

 public int methodOne(); 0 aload_0 [this] 1 getfield com.example.Test.local_int_one : int [13] 4 aload_0 [this] 5 getfield com.example.Test.local_int_two : int [15] 8 iadd 9 istore_1 [total] 10 iload_1 [total] 11 ireturn 

And here is the bytecode for methodTwo() :

 public int methodTwo(); 0 aload_0 [this] 1 getfield com.example.Test.local_int_one : int [13] 4 aload_0 [this] 5 getfield com.example.Test.local_int_two : int [15] 8 iadd 9 ireturn 

But note that this optimization is too small, and this readability of the code in this case is much more important than a few java instructions.

If you think that a temporary variable will make the code easier to read, then by all means, use it.

+5
source

Source: https://habr.com/ru/post/1232868/


All Articles