In Java you declare an array and then you call new to allocate space. so that a class with 4 named integers takes less space and has better locality than an array of size 4.
Is there any way to have an array of 4 elements, but have it allocated the same way as named vaiables a1, a2, a3, a4
For those that know C++, this is the same as asking for int x[4] as opposed to int *x
class X
{
int x1;
int x2;
int x3;
int x4;
};
[ Class OID ][x1][x2][x3][x4] = 1 ref + 4 int
class Y
{
int y[];
};
y=new int[4];
[ Class OID ][Y] ======> [Array OID][Array Size][y][y][y][y] = 3 ref + size + 4 int
Starting with Java 6, under ideal circumstances, objects are actually allocated on the stack rather than on the heap -- in other words, just what you're asking for. In general, this is attempted for objects whose references don't leave the scope in which they are created. So the truth is, in fact, that sometimes "new" is absolutely free! Although it may seem that Java code is verbose and inefficient, there are several layers of optimizing compilers that turn what you write into surprisingly efficient machine code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With