gleam-lang / stdlib

🎁 Gleam's standard library
https://hexdocs.pm/gleam_stdlib/
Apache License 2.0
492 stars 175 forks source link

Compute is_odd and is_even with bitwise op. #633

Closed antonio-petrillo closed 5 months ago

antonio-petrillo commented 5 months ago

These predicates can be implemented with a bitwise_and.
In binary all the digits are even (i.e. power of 2) except for the least significant bit, if such bit is set then number is odd otherwise it is even.
Usually using the bitwise operation result in fewer instruction to execute. If interested, more on bit manipulation can be found here. Have a nice day.

lpil commented 5 months ago

Hello! Have you benchmarked this change? It's not obvious to me that this would optimise the same way on the Erlang VM as it would with native compilation, especially since we've moved from a built-in operator to a function call.

antonio-petrillo commented 5 months ago

Nope, I didn't benchmarked it properly (and now I also feel really stupid XD). I will do it when I have a day off from work (hopely this weekend) if it is ok for you.

lpil commented 5 months ago

Thank you.

antonio-petrillo commented 5 months ago

Hi it's me again, I've done some benchmarks, and I guess you were right my implementation is not that great. I've done the following benchmarks (with glychee) on my laptop:

But the result are almost identical, typically the result are the following:

  1. my implementation of is_odd
  2. int.is_odd
  3. int.is_even
  4. my implementation of is_even

But in the best case (in favor of my solution) the difference was 0.0005 millisecond, I guess it's not worth it. Maybe one day when gleam can target baremetal, I would propose again (I'm joking).

Have a nice day. PS: thanks for the amazing work on gleam.

lpil commented 5 months ago

Cool, good to know! Thanks for testing