[plt-scheme] code speed

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Thu Jan 25 14:19:16 EST 2007

Joshua Zucker skrev:
> 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.

Try this:

(define (rvc-srfi-43 v n)
   (let ([v (vector-copy v)])
     (vector-reverse! v 0 n)))

On a vector v of length 1000000 and n=500000 I got a
factor 10 speed up.

-- 
Jens Axel Søgaard



Posted on the users mailing list.