Quantcast
Channel: The Open Code Project
Viewing all articles
Browse latest Browse all 10

Switch vs If – Which is faster?

$
0
0

In programming there are two different methods that people use to test variables that have a number of different values. One method is to use the If statement and define blocks of code to perform. The other common method is to use a switch statement and list all possible values, perhaps including a default value, and perform some process inside the appropriate section of code.

The question that people get stuck on is, besides making the code look prettier, which type of statement is better to use? Some people say If is faster, while others say Switch is. Obviously you should make your code look good, which is why Switch is commonly used, but if Switch causes your website or application to run slow then you wouldn’t want to use it.

So to answer this question, I’ve designed some code that tests each version in a very simple manner. The resulting number of milliseconds is written on the webpage after each section is done processing.

var start = (new Date).getTime();
var b = 0;
var a = 1;
for(var i=0; i<100000000; i++){
	if(a == 1){
		b++;
		a = 0;
	}else if(a == 0){
		a = 1;
	}
}
var diff = (new Date).getTime() - start;
	
document.write(diff+"<br />");
	
start = (new Date).getTime();
b = 0;
a = 1;
for(var i=0; i<100000000; i++){
	switch(a){
		case 1:
			b++;
			a = 0;
			break;
		case 0: 
			a = 1;
			break;		
	}
}
diff = (new Date).getTime() - start;
	
document.write(diff+"<br />");

Viewing all articles
Browse latest Browse all 10

Trending Articles