MCUdude / MicroCore

A light-weight Arduino hardware package for ATtiny13
539 stars 87 forks source link

Optimize shiftOut function a little #151

Closed marshfolx closed 1 year ago

marshfolx commented 1 year ago

I think the value of MSBFIRST and LSBFIRST should be changed to 0x80 and 0x01 respectively. Then a reduntant branch can be elimated to reduce code size. I have no idea if this has any side effect to existed code.

From this:

    if(bitOrder == MSBFIRST)
    {
      if(value & 0x80)
        PINB = datapinMask;
    }
    else
    {
      if(value & 0x01)
        PINB = datapinMask;
    }

To:

      if(value & static_cast<uint8_t>(bitOrder))
        PINB = datapinMask;
MCUdude commented 1 year ago

Hi @marshfolx!

Thanks for the suggestion! I haven't tried your code on actual hardware, but it seems like the compiler is clever enough to optimize the existing shiftOut function so that the compiled size is identical to the improvement you provided.

The compiler probably understands that the MSBFIRST/LSBFIRST argument is constant, and optimizes away the entire if-query.

There might be code out there that relies on MSBFIRST == 1 and LSBFIRST == 0, so I'm a bit hesitant to change these.

marshfolx commented 1 year ago

@MCUdude emmm,if so then I did agian some premature optimizations😂. I'm too lazy to find out the truth in assembly.