Which block of code will execute faster?

100 Views Asked by At

B1

if (this.id === 'username') {
  switch (this.value.length) {
    case  0:
    case  1:
    case  2:
      // 'Username must be at least 3 characters'
      break;
    case  3:
    case  4:
    case  5:
    case  6:
    case  7:
    case  8:
    case  9:
    case 10:
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
    case 16:
    case 17:
    case 18:
    case 19:
    case 20:
      // Another if else statement
      break;
    default:
      // 'Username must be at most 20 character'
  }
}

B2

if (this.id === 'username') {
  if (this.value.length < 3) {
    // 'Username must be at least 3 characters'
  } else if (this.value.length > 20) {
    // 'Username must be at most 20 characters'
  } else {
    // Another if else statement
  }
}

I would test this myself using browser developer tools, but unfortunately I'm a n00b to programming, and don't yet know how to use the developer tools all that well. Any input would be greatly appreciated.

2

There are 2 best solutions below

2
On BEST ANSWER

The second one is always the better choice for readability, and the performance benefit (if one even exists) would be marginal using a switch statement. The < / > operators are probably an instruction or two of native code, and I can't imagine that any switch statement would compile down to something so small.

I wouldn't even bother to test the difference; it shouldn't be worth your time unless you can prove that those few lines are the bottleneck in your program. (In which case, I would be exceedingly surprised.)

Also, if you're really concerned about good performance practices you could cache the length and achieve a small readability win too.

if (this.id === 'username') {
  var length = this.value.length
  if (length < 3) {
    // 'Username must be at least 3 characters'
  } else if (length > 20) {
    // 'Username must be at most 20 characters'
  } else {
    // Another if else statement
  }
}
0
On

It's negligible and really depends on the user's Javascript parser.

You should use the second option though as it's much better readability-wise, and much easier to change at a later date. Moreover if you're so concerned with performance the second is fewer characters too which means your site will load faster.