[plt-scheme] code speed

From: Joshua Zucker (joshua.zucker at gmail.com)
Date: Thu Jan 25 12:47:24 EST 2007

In an inner loop of something I'm working on, I had initially written
the following code:

    (build-vector (vector-length stack)
                  (lambda (x) (cond [(<= x n) (vector-ref stack (- n x))]
                                    [else (vector-ref stack x)]))))

to reverse the first n items of a vector.

I can make it slightly faster (I think) if I do it with mutation, but
I have to be careful because sometimes I really want a copy of the
vector, not a mutation ...

But then I saw that there were built-in functions for vector copying
and so on.  So I tried

(vector-append (vector-reverse-copy stack 0 (add1 n)) (vector-copy
stack (add1 n))))

and was very surprised to find that this was MUCH slower.

Maybe it's the allocation/deallocation of memory for the two vectors
that get appended together to make the final one?  Or too much
redundant copying going on?

Any suggestions are much appreciated.

--Joshua Zucker

Posted on the users mailing list.