Fix TextureCache memory leak and add is_empty() method (#14480)

# Objective

Fix a memory leak in `TextureCache` caused by the internal HashMap never
having unused entries cleared.

This isn't a giant memory leak, given the unused entries are simply
empty vectors. Though, if someone goes and resizes a window a bunch, it
can lead to hundreds/thousands of TextureDescriptor keys adding up in
the hashmap – which isn't ideal.

## Solution

- Only retain hashmap entries that still have textures.
- I also added an `is_empty()` method to `TextureCache`, which is useful
for 3rd-party higher-level caches that might have individual caches by
view entity or texture type, for example.

## Testing

- Verified the examples still work (this is a trivial change)
This commit is contained in:
Brian Reavis 2024-07-27 06:16:27 -07:00 committed by GitHub
parent e49527e34d
commit 724fe49c73
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -82,16 +82,22 @@ impl TextureCache {
}
}
/// Returns `true` if the texture cache contains no textures.
pub fn is_empty(&self) -> bool {
self.textures.is_empty()
}
/// Updates the cache and only retains recently used textures.
pub fn update(&mut self) {
for textures in self.textures.values_mut() {
self.textures.retain(|_, textures| {
for texture in textures.iter_mut() {
texture.frames_since_last_use += 1;
texture.taken = false;
}
textures.retain(|texture| texture.frames_since_last_use < 3);
}
!textures.is_empty()
});
}
}