0

I'm writing a C++ code to ESP8266 MCU in the Arduino platform and I'm trying to get my code as efficient as possible.

To operate other MCU via I2C, I need to configure his internals registers which store 8 bits. In order to set bit on/off, Im using and bitwise mask.

One way to do this is shifting bits and applying the bit wise & (and) mask this way Set the i-th bit to zero?.

But I also could store all 8 possible values of shifting ones in an array, access them directly and evict doing bit shifting.

Like this:

const unsigned int PINS[8] = {0x1,0x2,0x4,0x8,0x10,0x20,0x40,0x80};

...

pt = pt & ~(PINS[i]);

Instead of:

pt = pt & ~(1 << i);

I'm thinking that this could be worse depending on how the MCU's compiler will work on this. Accessing arrays through index cost more? Array values will be in the cpu registers? Am I overkilling optimization? There is another option?

Can you help me with insights about this question?

Victor Dolirio
  • 143
  • 1
  • 3
  • 11
  • 2
    *Am I overkilling optimization?* – yes. The first option (array) requires an indirection where the other (`1 << i`) is only a single operation on a value that is in a register anyway. – Swordfish Apr 28 '19 at 02:10
  • often, i is a constant and the compiler will evaluate `~(1 << i)` at compile time, too. – datafiddler Apr 28 '19 at 12:28

1 Answers1

2

If you are at (and need) this level of optimization you are at the point where you will need to decompile the code and see exactly what the compiler has constructed.

If you really want to optimize from there I'd suggest writing a custom assembly function that ensures the loop (it is in a tight loop right?) is optimal. This is a pain, but the optimization you are looking at is on the order of individual cycles.

Even at that point, this likely won't matter, optimizations like loop unrolling will be far more material than two fast operations.

tarkmeper
  • 767
  • 3
  • 12