Maybe use bitwise check in your engine?
PlugFox opened this issue · comments
Maybe use bitwise check?
void main() {
const limit = 10000000;
final stopwatch = Stopwatch()..start();
for (var i = -limit; i <= limit; i++) {
if (i.isEven == i.isOdd) {
throw Exception('OOOOOPS');
}
}
print('SDK: ${stopwatch.elapsedMilliseconds} ms');
stopwatch.reset();
for (var i = -limit; i <= limit; i++) {
if (i.isEvenBitwise == i.isOddBitwise) {
throw Exception('OOOOOPS');
}
}
print('Bitwise: ${stopwatch.elapsedMilliseconds} ms');
stopwatch.reset();
for (var i = -limit; i <= limit; i++) {
if (i.isEvenDivision == i.isOddDivision) {
throw Exception('OOOOOPS');
}
}
print('Division: ${stopwatch.elapsedMilliseconds} ms');
stopwatch.stop();
}
extension on int {
/// n ^ 1 is n + 1, then even
bool get isEvenBitwise => abs() ^ 1 == abs() + 1;
// n ^ 1 is not n + 1, then odd
bool get isOddBitwise => abs() ^ 1 != abs() + 1;
/// n % 2 is 0, then even
bool get isEvenDivision => this % 2 == 0;
// n % 2 is not 0, then odd
bool get isOddDivision => this % 2 != 0;
}
@arnemolland check with division is extra slow, about two times, we must use abs() ^ 1 != abs() + 1;
to check isOdd