0

I have a variable with values that I want to switch and do actions based on those values. Here is what I currently do:

switch(myvalue)
{
   case "action1_category1":
   doAction1();
   break;
   case "action2_category1":
   doAction2();
   break;
   case "action3_category1":
   doAction3();
   break;
   case "action4_category2":
   doAction4();
   break;
   case "action5_category2":
   doAction5();
   break;
   case "action6_category2":
   doAction6();
   break;
   ...
}

So, I am thinking why not divide the variable by two categories and do it like this:

if(myvalue.endsWith("category1")
{
    switch(myvalue)
    {
       case "action1_category1":
       doAction1();
       break;
       case "action2_category1":
       doAction2();
       break;
       case "action3_category1":
       doAction3();
       break;
      ...
    }
}
else
{
    switch(myvalue)
    {
       case "action4_category2":
       doAction4();
       break;
       case "action5_category2":
       doAction5();
       break;
       case "action6_category2":
       doAction6();
       break;
      ...
    }
}

Will this new approach increase or lower my performance? Thank you.

  • Use what you find the most readable. That will never lead to a performance problem. If you're really curious about performance, the first one is probably faster, because it's compiled to a HashMap lookup. – JB Nizet Aug 11 '18 at 16:06
  • First will check once, second will check twice, use first – azro Aug 11 '18 at 16:07
  • @JB Nizet, I did not know about the HashMap internal approach. That is actually brilliant. Thank you for the information/explanation. Please write an answer with the HashMap hint so that I accept it. –  Aug 11 '18 at 16:12
  • Thank you @azro. –  Aug 11 '18 at 16:13

1 Answers1

-1

Well, i'd go towards the first solution for micro optimization .... But now this philosophy is considered evil. Here is a hint

Sadbrute
  • 30
  • 7