dirkwhoffmann / virtualc64

VirtualC64 is a cycle-accurate C64 emulator for macOS
https://dirkwhoffmann.github.io/virtualc64
Other
353 stars 33 forks source link

Optimize readBit / writeBit functions in Disk class #745

Closed dirkwhoffmann closed 1 year ago

dirkwhoffmann commented 1 year ago

Many functions of the Disk class such as the following one utilize the modulo operator to compute bit positions.

   u8 _readBitFromHalftrack(Halftrack ht, HeadPos pos) const {
        assert(isValidHeadPos(ht, pos));
        return (data.halftrack[ht][pos / 8] & (0x80 >> (pos % 8))) != 0;
    } 

Although HeadPos is a signed type, pos is required to be non-negative:

bool
Disk::isValidHeadPos(Halftrack ht, HeadPos pos) const
{
    return isHalftrackNumber(ht) && pos >= 0 && pos < length.halftrack[ht];
}

Using the modulo operator on signed types is costly, however, even if the modulus is a power of 2:

Bildschirm­foto 2022-12-23 um 06 27 48

Work item: Replace the modulo operator by an AND operation in all functions that only accept a positive values as arguments.