pekko icon indicating copy to clipboard operation
pekko copied to clipboard

chore: avoid the double evaluation of entityId in ClusterSharding

Open Roiocam opened this issue 1 year ago • 2 comments

Found something we could optimized it.


DO NOT MERGE until I have added some tests for it.

Roiocam avatar Apr 30 '24 06:04 Roiocam

Seems like duplicate code, can it be abstracted

laglangyue avatar May 01 '24 05:05 laglangyue

Use the cacheable partial function, and then verify it works.


var calTime: Int = 0
def entityId(value: Any): String = {
  calTime = calTime + 1
  value match {
    case "wrong" => null
    case _ => String.valueOf(value)
  }
}

def extractEntityIdFromExtractor: PartialFunction[Any, Any] =
  new scala.runtime.AbstractPartialFunction[Any, (String, Any)] {
    var cache: String = _

    override def isDefinedAt(msg: Any): Boolean = {
      cache = entityId(msg)
      cache != null
    }

    override def apply(x: Any): (String, Any) = (cache, x)
  }

lazy val xx = extractEntityIdFromExtractor

lazy val yy: PartialFunction[Any, Any] = {
  case message if entityId(message) != null => (entityId(message), message)

}

assert(!xx.isDefinedAt("wrong"))
assert(!yy.isDefinedAt("wrong"))
calTime = 0
val health = "health"
println(xx.isDefinedAt(health))
println(xx(health))
println(s"caltime = $calTime")
println("=====")
calTime = 0
println(yy.isDefinedAt(health))
println(yy(health))
println(s"caltime = $calTime")



Roiocam avatar May 13 '24 05:05 Roiocam

@Roiocam is it ok to get this merged now?

pjfanning avatar Jun 04 '24 10:06 pjfanning

@Roiocam is it ok to get this merged now?

I have no objections to this, but it would be better if there were reviews from others.

Roiocam avatar Jun 04 '24 14:06 Roiocam