Which is more efficient, a Switch or If statement? I know it may depend on the details of the implementation, but for my purposes this is a very simple matter of not wanting to clutter my code with nested if statements for two simple conditions: for example, in a for loop i = 0 or i != 0 then do something. Is it appropriate/less or more efficient to use a Switch in the for loop? See code Examples Below:
for(int i = 0; i < loops; i++){
try{
switch(i){
case 0:
if(stringLength < chunkSize){
sTmp = new
String(s.substring(0, stringLength));
list.add(sTmp);
}else{
sTmp = new String(s.substring(0, chunkSize));
list.add(sTmp);
}
break;
//}else{
default:
if(nStringPosition2 > stringLength){
sTmp = new String(s.substring(nStringPosition1, stringLength));
list.add(sTmp);
}else{
sTmp = new String(s.substring(nStringPosition1, nStringPosition2));
nStringPosition1 = nStringPosition1+chunkSize;
nStringPosition2 = nStringPosition2+chunkSize;
list.add(sTmp);
}
break;
}
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException "+e);
break;
}
}
Thanks for your reply!