Of course, you can implement the comparison in different ways.
I did it as follows:
common block:
int a = 42;
int k = 17;
if:
if (a == 42)
k+=4;
else k+=5;
case:
switch (a) {
case 42: k+=4; break;
default: k+=5; break;
}
ternary:
k += (a == 42) ? 4 : 5;
They do not compile into one bytecode:
l *Tern*.class
-rw-r--r-- 1 stefan stefan 704 2012-04-27 14:26 CaseIfTern.class
-rw-r--r-- 1 stefan stefan 691 2012-04-27 14:26 IfTernCase.class
-rw-r--r-- 1 stefan stefan 728 2012-04-27 14:26 TernIfCase.class
However, the benefits of the switch come into play when you have several cases - not just 2.
If ternary and cascade in more than 2 cases.
/. Ternary -, if switch.
, .
:
0 if tern case
1 3.103 0.244 0.118
2 0.306 0.276 0.309
3 0.382 0.329 0.328
4 0.464 0.435 0.458
5 5.045 1.519 1.248
6 4.57 3.088 2.915
7 4.036 2.977 3.015
8 3.197 3.834 3.893
9 4.631 4.523 5.488
10 6.445 3.891 3.09

, , - 5 , .
, . - , , /case/trernary .
, :
public class CaseTernIf
{
public static int aORbIf (int a) {
if (a == 2)
return 4;
else return 5;
}
public static int aORbTern (int a) {
return (a == 2) ? 4 : 5;
}
public static int aORbCase (int a) {
switch (a) {
case 2: return 4;
default: return 5;
}
}
}
(Scala):
object IfCaseTernBench extends Benchcoat [List[Int], Seq[Int]] {
type I=List[Int]
type O=Seq[Int]
val name = "CaseTern"
def iGenerator (n: Int) : I = (for (x <- 1 to n) yield math.abs (random.nextInt (3))).toList
def takePart (li: I, n: Int) : I = li.take (n)
def ifTest (i: I) : O = i.map (CaseTernIf.aORbIf)
def caseTest (i: I) : O = i.map (CaseTernIf.aORbCase)
def ternTest (i: I) : O = i.map (CaseTernIf.aORbTern)
val list2bench: List [(String, I => O)] = List (
"if test" -> ifTest _
, "case test" -> caseTest _
, "tern test" -> ternTest _
)
def test = {
list2bench.foreach (algo => println (algo._2))
}
}
:
BenchCoat