0

I have a function that will return me one of 3 different values: 0, -1, 1 (or 0, 1, 2).

Condition1 is more likely than condition2, and condition2 more likely than non of the condition being true, hence the elseif

function [A] = example(...)
if condition1 == true
   A = 1;
elseif condition2 == true
   A = -1;
else
   A = 0;
end

I need to check the value A, when doing that, will it be more efficient to see if A is positive or negative, or either 1 or 2?

Example 1:

if A > 0
   % Do something
elseif A < 0
   % Do something else
else
   % Do nothing
end

Example 2:

 if A == 1
    % Do something
 elseif A == 2
    % Do something else
 else
    % Do nothing
 end

Witch example will be most efficient cycle wise?

Mikkel
  • 1
  • 1
  • 1
    Are you talking about C or MATLAB, as you marked both tags. If this is only about MATLAB (which I assume), please remove the C tag. Thank you – hbaderts Apr 09 '15 at 12:51
  • I've read that the compiler can make better optimisations with positive values (unsigned). – Hayden Apr 09 '15 at 12:53
  • 1
    The C was a mistake, has been removed. That would mean that the 0, 1, 2 would be more efficient? – Mikkel Apr 09 '15 at 13:05
  • The processor compares using logic gates and compares all bit together, so I guess there wont be any difference. – articuno Apr 09 '15 at 14:14
  • 1
    Related: http://stackoverflow.com/questions/24848359/which-is-faster-while1-or-while2 - Basically, the compiler / interpreter performs optimizations under the hood and so it is essentially going to be the same. Do whatever you feel is most comfortable. – rayryeng Apr 09 '15 at 15:13

1 Answers1

0

I would suggest that you're over-optimizing your code, and that either option will be almost exactly the same. If you're concerned, why not set up an experiment to time both options? You can use the function timeit that's built in to MATLAB to compare the two possibilities.

As well as comparing (-1, 1) and (1,2), you might like to compare

if A == 1
    % Do something
elseif A == 2
    % Do something else
else
    % Do nothing
end

with

switch A
    case 1
    % Do something
    case 2
    % Do something else
    otherwise
end

I suspect this will make more difference than (-1, 1) vs (1,2), but still very little.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64