I hope everyone will enjoy reading this.
I have two IF statements below
public int GetTax(Item item)
{
int tax=0;
if(item.Name.Equals("Book"))
{
tax = 10;
}
if(item.Imported)
{
tax += 5;
}
return tax;
}
I have converted above if condition to this.
public int GetTax(Item item)
{
return 5 * ((int)item.Name.Equals("Book") * 2 + ((int)item.Imported));
}
Which one do you think efficient? and justify why?
If compiled literally the 2nd method is more efficient, because there is no branching.
Whenever there is branching, there is some branch prediction, which could miss, and therefore cause the CPU to re-execute the machine instructions.
Having said that, depending on the compiler, what you have written may be simple enough for it to optimize to equivalent code. This does depend on the return type of what you call. If the return type is boolean, they are equivalent.
However, if for example,
item.Importedis actually of integer type, then the two examples you gave are not equivalent, and the compiler may not compile both to the same thing.Because optimization is very compiler-dependent. If it was important to minimize runtime, you will only know for sure if you benchmark the code.