[MLton] s->alignment considered harmful

Vesa Karvonen vesa.a.j.k at gmail.com
Thu Nov 1 08:28:14 PST 2007


On Nov 1, 2007 6:00 PM, Matthew Fluet <fluet at tti-c.org> wrote:
> As for tweaking the implementation of util/align.h, one difficulty is that
> align has "round up" semantics, not "round down".  So, a simple mask won't
> work.  On the other hand, we do assume that the alignment is a power of
> two, so maybe there are some bit operations that would be faster than an
> integer divide.

The current implementation is:

static inline size_t align (size_t a, size_t b) {
  assert (b >= 1);
  a += b - 1;
  a -= a % b;
  assert (isAligned (a, b));
  return a;
}

If you can assume that b is a power of two, you can optimize it to:

static inline size_t align (size_t a, size_t b) {
  assert (b >= 1 && b == (b & -b));  /* Also asserts that b is a power
of two. */
  a += b - 1;
  a &= -b;
  assert (isAligned (a, b));
  return a;
}

-Vesa Karvonen



More information about the MLton mailing list