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
}
}
2
solved Which block of code will execute faster? [closed]