Reusing case class instances

Suppose my application uses Move objects many times, for a long 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) 

These are 10 different possible Input s and 40 different Move s. Is there a way to ask the compiler to optimize these types by creating all possible Move once and reusing instances over time?

+6
source share
1 answer

You can use scalaz Memo :

 val moveCache = Memo.mutableHashMapMemo{ip: (Input, Player) => Move(ip._1, ip._2)} .... val myMove = moveCache((myInput, myPlayer)) 

Honestly, I doubt very much that this will have a significant impact 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.

+4
source

Source: https://habr.com/ru/post/980144/


All Articles