Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse instances of case classes

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 Inputs, and 40 different Moves. Is there a way to ask the compiler to optimise these types by creating all the possible Moves once and reusing the instances over time?

like image 774
OlivierBlanvillain Avatar asked Dec 25 '14 08:12

OlivierBlanvillain


People also ask

What type of objects are the best uses for case classes?

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.

What are use case classes?

Use case classes have use case instances or objects called scenarios that represent specific interactions. Scenarios represent a singe sequence of messages and actions.

How to Reuse objects in Java?

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.

What is a case class in Java?

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.


1 Answers

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.

like image 81
lmm Avatar answered Oct 11 '22 02:10

lmm