Memory performance improvement - don't create strings when you can instead hash the list! New ists are cheaper in-memory than new strings (only need to allocate "number of strings in list" pointers, and not "number of chars in all strings" chars)

This commit is contained in:
Yair Morgenstern 2023-07-18 18:28:04 +03:00
parent ed74b03ff3
commit d7b277b6b5
2 changed files with 8 additions and 5 deletions

View File

@ -63,7 +63,7 @@ class TileMap(initialCapacity: Int = 10) : IsPartOfGameInfoSerialization {
var ruleset: Ruleset? = null var ruleset: Ruleset? = null
@Transient @Transient
var tileUniqueMapCache = ConcurrentHashMap<String, UniqueMap>() var tileUniqueMapCache = ConcurrentHashMap<List<String>, UniqueMap>()
@Transient @Transient
var tileMatrix = ArrayList<ArrayList<Tile?>>() // this works several times faster than a hashmap, the performance difference is really astounding var tileMatrix = ArrayList<ArrayList<Tile?>>() // this works several times faster than a hashmap, the performance difference is really astounding

View File

@ -844,14 +844,17 @@ open class Tile : IsPartOfGameInfoSerialization {
private fun updateUniqueMap() { private fun updateUniqueMap() {
if (!::tileMap.isInitialized) return // This tile is a fake tile, for visual display only (e.g. map editor, civilopedia) if (!::tileMap.isInitialized) return // This tile is a fake tile, for visual display only (e.g. map editor, civilopedia)
val terrainString = allTerrains.joinToString(";") { it.name } val terrainNameList = allTerrains.map { it.name }.toList()
val cachedUniqueMap = tileMap.tileUniqueMapCache[terrainString]
terrainUniqueMap = if (cachedUniqueMap != null) cachedUniqueMap // List hash is function of all its items, so the same items in the same order will always give the same hash
val cachedUniqueMap = tileMap.tileUniqueMapCache[terrainNameList]
terrainUniqueMap = if (cachedUniqueMap != null)
cachedUniqueMap
else { else {
val newUniqueMap = UniqueMap() val newUniqueMap = UniqueMap()
for (terrain in allTerrains) for (terrain in allTerrains)
newUniqueMap.addUniques(terrain.uniqueObjects) newUniqueMap.addUniques(terrain.uniqueObjects)
tileMap.tileUniqueMapCache[terrainString] = newUniqueMap tileMap.tileUniqueMapCache[terrainNameList] = newUniqueMap
newUniqueMap newUniqueMap
} }
} }