R – Immutable functional objects in highly mutable domain

functional programmingimmutability

I'm currently learning functional programming in my spare time with Scala, and I have an idle newbie question.

I can see the elegance of having immutable objects when doing something like calculating a Haar wavelet transform – i.e. when the data itself being represented by the objects doesn't change.

But I saw a blog where someone had a small game as an example when demonstrating immutability. If a creature object recieved damage, it didn't change its state – it returned a new creature object with the new hitpoints and a new "aggro towards X" flag. But if we were to design something like a MMORPG, World of Warcraft say. A hundred players in a battleground… possibly thousands of attacks and buffing/debuffing spell effects affecting them in different ways. Is it still possible to design the system with completely immutable objects? To me it would seem like there would be a ginormous swarm of new instances each 'tick'. And to get the currently valid instance of objects, all clients would constantly have to go through some sort of central "gameworld" object, or?

Does functional programming scale for this, or is this a case of "best tool for best job, probably not immutable here"?

Best Answer

To me it would seem like there would be a ginormous swarm of new instances each 'tick'.

Indeed, that is the case. I have a Haskell application that reads a market data feed (about five million messages over the course of a six-hour trading day, for the data in which we're interested) and maintains "current state" for various things, such as the most recent bid and offer prices and quantities for the instruments, how well our model fits the market, etc. etc. It's rather frightening to simulate a run of this program against a recorded feed in profiling mode and watch it allocate and GC close to 288 TB of memory (or close to 50,000 times the size of my machine's RAM) in the first 500 seconds of its run. (The figure would be considerably higher without profiling, since profiling not only slows down the application, but also forces it all to run on one core, as well.)

But keep in mind, the garbage collector in pure language implementations is optimized for this sort of behavior. I'm quite happy with the overall speed of my application, and I think that it's fairly demanding, in that we have to parse several hundred messages per second from the market feed, do some fairly extensive calculations to build our model, and use that model to generate orders to go to the exchange as quickly as possible.