[MLton] Vector.fromList[] performance

Benoit Hudson benoit.hudson at gmail.com
Tue Oct 24 12:19:02 PDT 2006


I have a largeish program that uses vectors a lot: it's a geometry
code that is written in arbitrary-dimensional fashion.  Some of the
code is in special dimension, so I often find myself converting tuples
(x,y) into vectors using Vector.fromList[x,y].

Unfortunately, the performance of this utterly sucks: I don't know how
to read the generated bytecode to see exactly what's happening, but I
can't fathom how it could be so bad without paying for building the
list, then converting it to a vector.  In the program below, I notice
a 10x degradation over C.

How hard would it be to special-case Vector.fromList on a literal
list?  SML/NJ allows this using the #[] construct, which helps SML/NJ
on this test program knock the pants off mlton.  But really the
compiler should just handle it automatically so that I can write
standard-compliant code.

The test case follows.  The idea is to make a loop that can't be
optimized away, and that uses a vector that can't be optimized away.
Timings on my OSX / G4 1.25 GHz box are:
mlton-20051202: 4.15s
SML/NJ 110.58: 2.75s
SML/NJ 110.58: 1.11s (using # instead of Vector.fromList)
gcc-3.3 -O0 : 0.91s
gcc-3.3 -O3:  0.37s

----------------
fun vectors(i: int, sum) =
  let
    val v = Vector.fromList[i, 1+sum, 5*sum*sum, 6*i, 2*i]

    val sumadd = Vector.sub(v, sum mod 5)
    val sum = (sum + sumadd) mod 763
  in
    if i = 1 then sum else vectors (i-1, sum)
  end
val _ = print (Int.toString (vectors (10000000, 0)) ^ "\n")

-----------------
#include <stdio.h>

int vectors(int i, int sum) {
  while (i > 0) {
    int v[] = { i, 1+sum, 5*sum*sum, 6*i, 2*i };
    int sumadd = v[sum % 5];
    sum += sumadd;
    sum %= 763;
    i--;
  }
  return sum;
}
int main() {
  return !printf("%u\n", vectors(10000000, 0));
}

-- Benoît



More information about the MLton mailing list