If statement faster than the ternary operator?

Hi everybody,

I’d like to know which is faster or have a better performance between :

if (flag) {
  var v = "something";
} else {
  var v = "else";
var v = (flag) ? "something" : "else";

And how do you know the answer? Did you do a relevant test? Have you read it somewhere?


var start = (new Date()).getTime();
//...code here to time goes here
var elapsed = (new Date()).getTime() - start;

elapsed will be miliseconds.

You generally want to put a big loop between the start and end markers.



<script type="text/javascript">
var start = (new Date()).getTime();

var flag = false;

for (i=0; i<10000000; i++) {

//	if (flag) {
//		var v = "something";
//	} else {
//		var v = "else";
//	}

	var v = (flag) ? "something" : "else";


var elapsed = (new Date()).getTime() - start;

alert (elapsed);


IF   - Ternary
4204 - 4182
4239 - 4155
4187 - 4261
4162 - 4197

i.e. nothing in it. :slight_smile:

It may also depend on how often the statements have to test both values.
This example sets flag to 0 half the time.

function iftest(n){
	var start= +(new Date());
	var flag, v;
		flag= n%2;
		if(flag) v= "something";
		else v= "else";
	return new Date()- start;

function terntest(n){
	var start= +(new Date());
	var flag, v;
		flag= n%2;
		var v= (flag)? "something": "else";
	return new Date()- start;

function testboth(n){
	var results=[];
	results[0]= 'if='+iftest(n);
	results[1]= 'tern='+terntest(n);
	return results;


Trying that approach, as you increase the number of loops then the IF method starts to edge ahead.

It would depend on exactly how you are using it. There would be situations where either would be faster than the other but the time difference is so small you’d need a huge number of calls to even be able to record any difference and a page that takes days to download on broadand before your visitors would actually notice any difference in the time those statements take.

If you are looking to optimise code then you should look at those parts where a small change has a significant effect.

The difference in speed will always be marginal, and therefore irrelevant. The decision of which to use is down to code readability/maintainability.

Actually, I’ve already done this kind of tests, got the same kind of results and deduced the same thing. I just need another point of view.

“readability/maintainability” is the main point to choose which one I’ll use.

Thanks to everybody.

Except for when you have significant issues with run times readability/maintainability should always be the reason for deciding on which approach to take. So start with nice readable easy to maintain code and only change it if you really need to for performance.

The ternary operator can make code easier to read where the purpose is to select one of two or more values to assign to a variable just as a switch/case makes it easier to read where you are testing a single field for a number of different values.