Reputation: 8559
Consider the following two pieces of code:
var adj=0>grip.y?0<grip.x?0:-180:0<grip.x?-360:-180;
and
var adj;
if (grip.y < 0) {
if (grip.x > 0)
adj = 0;
else
adj = -180;
}
else {
if (grip.x > 0)
adj = -360;
else
adj = -180;
}
They both produce the same result, but which is faster?
Upvotes: 0
Views: 1867
Reputation: 163
Just to check the performance in JavaScript, I tried to do a small experiment.
console.time("ternary operator");
const val = (5 > 2) ? true : false;
console.timeEnd("ternary operator");
console.time("if condition");
let val2;
if (5 > 2) {
val2 = true;
} else {
val2 = false;
}
console.timeEnd("if condition");
and the output is quite shocking as the if
condition is almost twice faster than the ternary statements.
So to conclude I would suggest using the if
condition over the ternary operator.
Ok so here is multiple tries of similar operation
Upvotes: 0
Reputation: 3298
Use switch conditions,that is faster than if and other conditional statements.
Upvotes: 0
Reputation: 172398
The speed difference will be negligible - use whichever you find is more convinient and readable. There wont be any problem with the wrong conditional construct.
Upvotes: 2