API design: assigning additional values to objects

Ok, so this is the problem: I have 2 modules, the first is a general API, and it contains a class called Image. The second, is a small game engine (built on top of LWJGL and etc), and it have classes for image loading and rendering.

For the first API, it is somewhat like the Java Image API: you can load an Image object from streams, and it will have it’s model (with all the data, pixels, etc) loaded onto the memory. And, for the second API, it actually takes these Image objects, generates a buffer of them, and uploads to the GPU via OpenGL, then storing the texture ID for later use.

The problem is: since the Image class is from another API, and I cannot (actually, shouldn’t) do any changes, then I cannot create a field just for storing the texture ID.

When everything was in the beginning, I did the basic and easy solution: use a Map to store entries of Image:TextureID. But, since I’m constantly using the Images to render to the screen every frame, I had to constantly lookup on the Map to get the TextureID related to that Image.

Of course it was fckng performance (benchmarked: 14.5% of CPU time per tick). Then I HAD to find another way to store a TextureID for Images.

What I did for now: created, in the first API, a class named Storable, which have one field named “stored” of type Object, and methods getStored(), hasStored() and setStored(). Then, I made Image a subclass of Storable.

This way, I can store the Texture IDs for the Images in a “generic” way, so that the first API will not be dependent on the second.

Ok, this worked for my problem, but still, if I want to store an object reference (in my case, the texture ID) into another object, the object class must be a subclass of Storable. To the question: is there another, maybe safer, maybe more dynamic, maybe via JNI, solution to this problem, so that I can store a few bits of additional data in ANY object?

HashMaps actually usually have a complexity time of O(1) (absolute worst case scenario where all the hashcodes are the same is O(n)), so they shouldn’t be that slow. Just because you benchmarked it at a percentage of CPU time doesn’t mean it actually took a long time - the tick itself could’ve been really fast.

Try using the Maps again, and benchmark it with time, not CPU percentage. It should be negligible/really really small.

But for your actual question: do you really need to go full-on overboard just to store some more data in an object? You can simply make an object such as ImageWithId and store the Image and texture ID. Don’t overcomplicate it.