Skip to content

Conversation

@dstahlke
Copy link
Contributor

@dstahlke dstahlke commented Dec 1, 2025

This is a proof-of-concept for expression templates. If we go this route, it'd be a major redesign but should not require any changes to user code (API reverse compatibility).

  1. Expression templates mean that operations like a & b will return a type BBExpr<...> that implements lazy evaluation.
  2. Things like (a & b).popcnt() or a = b & ~c can be done without allocating any BitSet temporary objects. Furthermore, an optimizing compiler will be able to inline the operations and holistically optimize the whole statement. Debug builds will be slow because inlining is turned off.
  3. Almost all methods should eventually move from BitSet to BBExpr and BBExprMutable. This will allow these methods to be used on expressions, e.g., (a & b).popcnt(). New containers, such as statically-sized bit vectors that live on the stack, can simply inherit from BBExpr and implement bbexpr_num_blocks() and bbexpr_get_block() to be blessed with all these methods.
  4. BBExpr can be iterated over: for (int i : bbvec) or for (int i : (a & ~b)). Consequently, BBScan can be deprecated. Possibly BBObject can be deprecated as well.
  5. Speed seems to be about the same. An ISEQ benchmark indicates that various versions are about 10-20% faster or slower in a somewhat unpredictable way. This benchmark is in src/bitscan/tests/test_bbexpr.cpp. It's notable that the fastest version is (IMHO) also the most readable.
  6. I think the only downside is you have to be sure to not capture expressions into a variable that outlives one of the arguments. This mostly happens if people use auto. Example: auto a = b & c; b.clear(); would be a problem because a would hold a reference to b and c but BitSet a = b & c; b.clear(); would be okay. (I'm assuming BitSet having a hypothetical clear() method that releases memory.) All C++ linear algebra libraries have the same problem because they all use expression templates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant