Suppose my application uses a lot of Move
objects over and over durring a long period of time, where Move
is defined as follows:
sealed trait Player
case object P1 extends Player
case object P2 extends Player
case object P3 extends Player
case object P4 extends Player
sealed trait Key
case object Up extends Key
case object Down extends Key
case object Right extends Key
case object Left extends Key
case object Space extends Key
sealed trait Action
case object Press extends Action
case object Release extends Action
case class Input(key: Key, action: Action)
case class Move(input: Input, player: Player)
That's 10 different possible Input
s, and 40 different Move
s. Is there a way to ask the compiler to optimise these types by creating all the possible Move
s once and reusing the instances over time?
Case classes work great for data transfer objects, the kind of classes that are mainly used for storing data, given the data-based methods that are generated.
Use case classes have use case instances or objects called scenarios that represent specific interactions. Scenarios represent a singe sequence of messages and actions.
Another way to reuse objects is by means of ThreadLocal variables which will provide distinct and time-invariant instances for each thread. This means normal performant memory semantics can be used.
Case classes are like regular classes that have default apply() method which handle object construction. There is no need to use a new keyword to create an object. Case class provides purely functional code with immutable objects. Case classes are a representation of a data structure with the necessary methods.
You could use a scalaz Memo
:
val moveCache = Memo.mutableHashMapMemo{ip: (Input, Player) => Move(ip._1, ip._2)}
....
val myMove = moveCache((myInput, myPlayer))
Honestly I very much doubt this would have a significant effect on performance. Before making your code less readable, make sure you have clear profiling results that show that it actually makes the difference you think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With