E
E
Eirenliel2013-04-15 20:10:05
Java
Eirenliel, 2013-04-15 20:10:05

Structures in JAVA - what am I doing wrong?

Everyone knows that Java does not support structures and will not. To avoid misunderstandings, what I mean by structures: in fact, this is a lightweight class that has only fields that lie in a certain order and the structure has a size equal to the sum of the sizes of the fields. So, for example, this structure:

struct MyStruct {
int field1;
int field2;
long field3;
byte field4;
}
It takes 17 bytes in memory, no more, no less + a link to it. In Java, classes take longer, that's known.

In general, the bottom line is that I really need to store data in chunks of 11 bytes. At the same time, store them in a hashmap. That is, there are two options in Java - to store an array of 11 bytes in a hashmap or an object with the necessary fields. An array is more convenient.

But the idea occurred to me to allocate 11 bytes of memory through sun.misc.Unsafe and store a link to the memory area in the hashmap. Using the trove library, the link "weighs" only 8 bytes, because trove stores primitive types. The object would "weigh" another 16 bytes per header + would be aligned.

By all measurements, it turns out that a hashmap of a million elements using such a strange scheme is filled 2 times faster than with 11-byte arrays, reading and writing is also faster, but not much. Obviously, I don’t know how to do tests and I don’t know something, because it probably shouldn’t work like that ...

In general, what am I missing? After all, obviously this method should be worse, I don’t know all the subtleties, tell me, please.

Yes, I know that you can’t do this, they write it wrong in Java and all that. I just know how to write in java, but sometimes you need to go beyond normal use ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
leventov, 2013-04-16
@Eirenliel

I highly recommend watching the recording of the JUG.ru meeting with Roman Elizarov - Millions of quotes per second in pure Java . The main topic of the lecture is just "structures" in Java. There are answers to all the questions that you voiced in this thread, and much more.
On the subject: the allocation itself is definitely not something that should be “optimized” under the current Hotspot.

G
Gribozavr, 2013-04-15
@gribozavr

If you want to do curly cutting by bytes:
1. Think, maybe it's not worth it?
2. docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html But note that non-x86 unaligned reads/writes can be expensive.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question