Costs of local variables vs operand stack size when writing method in Java byte code

Viewed 806

I am currently working on a tool that produces Java byte code directly. When considering performance, I could for example translate the following Java equivalent

int[] val = new int[1];
val[0] = 1 + 1;

in two different ways. Without applying optimizations, I could translate the stated code into the following byte code equivalent

ICONST_1
ANEWARRAY I
DUP
ICONST_1
ICONST_1
IADD
AASTORE

where the array would in the end be the only value on the operand stack. This translation requires an operand stack size of 4 since there is a maximum of four values (int[], int[], int, int) on the stack but this solution would not consume any local variable slots.

I could however also translate the code snippet like this:

ICONST_1
ICONST_1
IADD
ISTORE_1
ICONST_1
ANEWARRAY I
DUP
ILOAD_1
AASTORE

This translation would reduce the size requirement for the operand stack by one slot but instead it would cost a local variable slot for storing the intermediate result.

Not thinking of the reusability of such slots and local variables within a method: How should I consider the costs of the operand stack versus the local variable array? Is operand stack size cheaper since it is not random access memory?

Thank you for your help!

2 Answers
Related