1

I'm trying to clean up a PAC file. Which of the following code blocks are more concise and/or faster?

if (host == "localhost")                                  {return "DIRECT";}
if (shExpMatch(host, "localhost.*"))                      {return "DIRECT";}
if (host == "127.0.0.1")                                  {return "DIRECT";}
if (isPlainHostName(host))                                {return "DIRECT";}
if (isInNet(hostIP, "10.0.0.0", "255.0.0.0"))        {return "DIRECT";}

versus

if ( host == "localhost" ||
     host == "127.0.0.1" ||
     shExpMatch( host, "localhost.*" ) ||
     isPlainHostName( host ) ||
     isInNet( hostIP, "10.0.0.0", "255.0.0.0" ))
return "DIRECT";

I'm assuming that if the target host is indeed "localhost," then the first would be faster, as it would hit the return right away and not need to evaluate the remaining conditionals. But assuming none of the conditions are true, which method is preferred?

Joe Fruchey
  • 379
  • 3
  • 10
  • 2
    FYI JavaScript is *short circuited* so with an *or* the first `true` condition halts further evaluation. As for which is better I honestly thinks it makes zero difference. – Alex K. May 12 '15 at 15:17

1 Answers1

2

The second option is faster, because it doesn't have to jump the multiple return-statements. As Alex K. mentioned in his comment, the first true statement in the or-cascade halts evaluation.

Johannes Reuter
  • 3,501
  • 19
  • 20