Sharing my tests on a number increment: "if" vs "%", speed vs simplicity

Hello there,

in my project I needed to increment byte or reset it to 0 if it overflows, I bet you already know the code:

if (Byte1 < MaxByte - 1)
  {
    Byte1++;
  }
  else
  {
    Byte1 = 0;
  }

But later I needed a function to increment more than 1 at a time, so I came up with this code (it works with any increment value [IncValue] ):

Byte2 = (Byte2 + IncValue) % MaxByte;

But disadvantage is that ‘%’ about 11 times slower than first example (I run both codes 100 000 times – first took 133ms, 2nd 1462ms)

Then I came up with this:

 if ( Byte3 + JumpEvery < MaxByte )
    {
      Byte3 = Byte3 + JumpEvery;
    }
    else
    {
      Byte3 = Byte3 + JumpEvery - MaxByte;
    }
  }

100 000 times –187ms, best of both worlds, tho a bit more complicated than 2nd example, but it’s ~8 times faster.

Time is important in my code so I needed to find best way and I think some people may find this interesting.

Please don’t hesitate if you want to add something :slight_smile:

P.S. also I’m making Arduino IDE theme:

Hello - if you really use a variable of type "byte" is is enough to use the simple increment without all other tests.

"byte" is an 8-bit unsigned type, at 32-bit controllers too. If you use Byte1++, Byte1 holds after 255 the value 0.

If I use "byte" that doesn't mean max number is 254, actually it's 7 in this case, but yes, I'm aware of overflow.