chunky icon indicating copy to clipboard operation
chunky copied to clipboard

Cache TextureMaterial to prevent their proliferation

Open aTom3333 opened this issue 4 years ago • 1 comments
trafficstars

A number of entities need to create TextureMaterial to wrap their Texture when calling primitives. The issue is that a lot of those TextureMaterial are created from the same Texture meaning they are distinct instances that are identical.

I have added a TextureMaterial cache to ensure a single TextureMaterial instance exist for a given Texture, doing this divides the number of TextureMaterial instances by 10, saving memory. Additionally, by not using the cache for Textures that I know aren't shared (like the SignTexture, cf second commit), the cache is not filled with entries that won't bring any benefits and stays small.

To implement the cache I needed a hash map where the values were weak references (the built-in WeakHashMap has weak keys but strong values) so I added a new dependency on apache common collections. You decide if that is acceptable.

For 1 region of greenfield, I went from 90k TextureMaterial instances to 9k going from 5MB to 500kB. For 4 regions of greenfield, I went from 160k TextureMaterial instances to 16k, going from 9MB to 900kB.

The additional memory overhead of the cache is was only of 35kB for 1 region of greenfield (didn't measure for 4 regions).

The savings don't seem to scale that much and aren't that big but that's probably still worth it.

Another benefit of reducing the number of instances of Material is for an hypothetical BVH implementation that wants to store the primitives compressed by replacing the material by an index into a palette of materials, having less instances of Material would reduce the size of this palette.

aTom3333 avatar May 22 '21 19:05 aTom3333

The weak keys part… The existing TextureCache is buggy then :scream:

leMaik avatar May 29 '21 21:05 leMaik