I am trying to write a tutorial game in Scala & Processing, intending to use as much FP as possible. However, I come to a conclusion that immutable-state game objects are not profitable in such application. If an object is big, it may result in quite intensive memory consumption in case of numerous such objects being constantly updated (therefore, making copies of itself each cycle), for example, using the copy() func. What is the default approach to resolute this? The only thing that I come up with – is to slice the object in tiny pieces-objects so that only those who need to be updated, are updated while leaving the “big” objects same.
I am trying to write a tutorial game in Scala & Processing, intending to
Share
A game engine is essentialy a (discrete) event simulation. Typically, these are implemented via mutable data structures such as heap for the events, quad/oct trees for spatial queries about objects and lots of hash tables.
For each of these data structures, mutable variants are faster. Furthermore, immutable data structures produce garbage which has to be collected, so the pressure on the GC is higher, and your application ends up being slower. Where real-time is a concern, GC pauses can be harmful (e.g. it may affect the framerate in your game), and this is particularly the case on platforms with less processing power, such as Android.
As for the
copy()method – it doesn’t have to copy the entire object to create the updated version. If your object is organized hierarchically in a tree-like manner (e.g. as a hierarchy of case classes), then changing one property of the object requires rewriting only one path in this tree – you won’t need to rewrite everything. Still, it will be more costly than just having a mutable version and updating in-place.Example:
To add more ammo to the weapon, you don’t have to copy the entire
World:In this example,
map, otherplayers, and theshieldof the modifiedPlayerstay the same in memory and are not eagerly copied.I would advise going for a mutable data structure to represent the state – unless you have a concurrent game engine with (for example) a single writer that simulates the game state, and a range of readers which render output, handle sound, network and so on, the benefits of immutable data structures are close to none in this use case.