TomUk
TomUk

Reputation: 11

Is there a performance hit in ios development using If statements?

I'm trying to debug my games code. I'm developing a game for iOS and my code uses a lot of IF statements. I would like to know if there is even a very small performance hit when using these.

Thanks

Upvotes: 0

Views: 153

Answers (2)

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

It depends on where you used your if statements, there are some performance regarding using if in the right way

I will state some of them

  • Always use the if that is most likely to happen before the else, use the cases that are more common before then use the ones that are less likely
  • try to use if before the loops, For example

instead of this

BOOL isCase1 = [self isCase1];
for (int i = 0 ; i < 10000 ; i ++)
{
   if(isCase1)
   {
       //do something
   }
   else
   {
      //do some other thing
   }
}

use this

   BOOL isCase1 = [self isCase1];

   if(isCase1)
   {
       for (int i = 0 ; i < 10000 ; i ++)
       {
       }
   }
   else
   {
       for (int i = 0 ; i < 10000 ; i ++)
       {
       }
   }

Dont assume that you will need to improve performance before you are sure, most of the time your performance is doing good, if you are sure that some code is causing performance issues improve it (dont premature optimize your code)

These are some of the cases, there are much more

UPDATE:

Some other helpful things you could do, cache your boolean checking statments

for example

Instead of

for (int i = 0 ; i < 10000 ; i ++)
{
   if([self isCase1]) //Do some thing
}

use

//Cache the result inside a variable
BOOL isCase = [self isCase1];
for (int i = 0 ; i < 10000 ; i ++)
{
   if(isCase) //Do some thing
}

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

Of course there is a performance hit when branching.

But you can't make a reasonable program without branch.

So use the if, and if by profiling your program you detect a problem on a specific location in your code, try to see if you can reduce the numbers of branchings or to put them out of the loops. But don't pay too much attention to it as long as the code remains clear.

Most of the time, the first impact of numerous if is on readability and maintainability. But premature optimization is often a greater hit on those topics.

Upvotes: 2

Related Questions