In one of the projects at my university I am working directly with Java bytecode.
After browsing the list of instructions available for the JVM (http://en.wikipedia.org/wiki/Java_bytecode_instruction_listings) I saw that there is no such thing as [b|c|s]store,
only istore
for storing integers in a local variable. Does it mean that if in my program I write:
short a;
int b;
I am not saving any memory, because every local variable entry occupies 4 bytes?
I was always under the impression that using short
or byte
types will save some memory at runtime.
This is explained in section 2.11.1 of the JVMS:
Note that most instructions [...] do not have forms for the integral types byte
, char
, and short
. None have forms for the boolean
type. A compiler encodes loads of literal values of types byte
and short
using Java Virtual Machine instructions that sign-extend those values to values of type int
at compile-time or run-time. [...] Thus, most operations on values of actual types boolean
, byte
, char
, and short
are correctly performed by instructions operating on values of computational type int
.
It is justified thus:
Given the Java Virtual Machine's one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine's run-time data types, there would be more instructions than could be represented in a byte. Instead, the instruction set of the Java Virtual Machine provides a reduced level of type support for certain operations. In other words, the instruction set is intentionally not orthogonal. Separate instructions can be used to convert between unsupported and supported data types as necessary.
However, whilst this applies to load/store of stack variables, it doesn't apply to load/store into primitive arrays; there are opcodes for all primitive types.
You are not saving any memory using a local int
vs long
as these are likely to be in 64-bit registers. Note: how the byte code is laid out and how the code is actually run is not the same.
Saving two bytes is not important on any new hardware. The value of 2 bytes is less than 1/1000 the time it takes you to blink even if you are on minimum wage.