elm
elm

Reputation: 20415

Scala if-else efficiency improvements

The following snippet is invoked few million times in an application,

val res = myArray.map { case (expr1,expr2) =>
  val nan1 = expr1.isNaN
  val nan2 = expr2.isNaN

  if (nan1 && nan2) 0.0
  else if (nan1  && !nan2) expr2
  else if (!nan1 && nan2) expr1
  else expr1-expr2
}

where myArray often contains between 100 and 1000 pairs.

Is there a way to make it (even) faster ?

Upvotes: 1

Views: 232

Answers (2)

Dmitry Leskov
Dmitry Leskov

Reputation: 3165

If this is the performance bottleneck, consider using a pair of arrays of the respective primitive type (Double?) over an array of pairs, and write a good old while loop, as @wingedsubmariner suggested.

To answer your original question, assuming that NaNs are rare, you can get marginal speedup by reordering the if-elses so as to identify the most common case first, not least because of branch prediction:

if (!nan1 && !nan2) expr1-expr2
else if (nan1) if (!nan2) expr2 else 0.0
else expr1

or maybe:

if (!nan1)
  if (!nan2) expr1-expr2 else expr1
else 
  if (!nan2) expr2 else 0.0

But you may have to reduce this snippet to a microbenchmark and measure it using something like JMH to notice the difference.

Upvotes: 2

gexicide
gexicide

Reputation: 40068

You can leave out &&!nan2 and !nan1 &&, since you are already sure that not both are true (tested above). However, the optimizer might notice this too and remove the code for you, so I doubt it would impact performance.

Upvotes: 0

Related Questions