Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common resources in static attributes

I would like to ask a question about static attributes. I am going to explain it with an example of what I came across.

I'm developing a videogame in which I have to create new objects every few seconds. For it, I'm using a pool, etc, but even using a pool and re-using objects, is still quite an expensive operation for the memory. So I ended up wasting all the memory creating this objects.

Trying to optimize the code, I realized in the new of this object, there are a lot of expensive operation like creating new textures, animations, and so on. Then I realized all this textures, animations, etc, are common for every object of this kind, so I thought in putting all the common stuff in static attributes.

Now my question is: where in the memory are the static attributes saved? Every time I create a new object of this kind, the static attributes are duplicated? Or there are just one static attributes for all of them? I guess is the second, makes a lot more sense, but I would like to be sure.

What do you think about the solution I proposed?

Thanks!!

like image 486
Frion3L Avatar asked Jul 25 '26 20:07

Frion3L


2 Answers

See the Java tutorial:

Every instance of the class shares a class variable, which is in one fixed location in memory.

Your solution is reasonable. You'd save a lot of memory.

A slight improvement would be to still have an instance field for the texture, (etc...), but to have that field point to a single static texture. You "waste" a few bytes per field, but there is still only one big item (the texture) in memory. The advantage is that if, in the future, you want a few of the objects to have a different texture, you can do that. e.g.

public class MyThing {

   // save memory by only having one each
   static final Texture SHARED_TEXTURE = createTextureSomehow();
   static final Animation SHARED_ANIMATION = createAnimationSomehow();

   // instance variables, by default everybody shares the same ones...
   private Texture texture = SHARED_TEXTURE;
   private Animation animation = SHARED_ANIMATION;

   ...

   // for a special MyThing, like the nastiest Zombie, you can change the texture...
   public void setTexture(Texture newTexture) {
      this.texture = newTexture;
   }

}
like image 37
user949300 Avatar answered Jul 27 '26 08:07

user949300



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!