[racket] dynamic compilation

From: Robby Findler (robby at eecs.northwestern.edu)
Date: Fri Jan 20 20:52:38 EST 2012

On Fri, Jan 20, 2012 at 5:58 PM, Danny Yoo <dyoo at cs.wpi.edu> wrote:
> For the upcoming version of WeScheme, I'm planning to use the real
> 'compile' from Racket.  I'm trying to better understand a part of the
> compilation system.  Here's a sample program I'm using to play:
>
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> #lang racket/base
>
> (define ns (make-base-namespace))
> (define (do-compilation program)
>  (parameterize ([current-namespace ns]
>                 [read-accept-reader #t])
>    (define bytes (compile (read-syntax #f (open-input-string program))))
>    (define op (open-output-bytes))
>    (write bytes op)
>    (get-output-bytes op)))
>
> (define (do-compilation/fresh program)
>  (parameterize ([current-namespace (make-base-namespace)]
>                 [read-accept-reader #t])
>    (define bytes (compile (read-syntax #f (open-input-string program))))
>    (define op (open-output-bytes))
>    (write bytes op)
>    (get-output-bytes op)))
>
> (time
>  (for ([i 1000])
>   (void (do-compilation "#lang racket/base\n\n(printf \"Hello world\")"))))
>
> (time
>  (for ([i 1000])
>   (void (do-compilation/fresh "#lang racket/base\n\n(printf \"Hello
> world\")"))))
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
>
> I see that the first do-compilation, the one that shares a namespace,
> runs faster than the version that generates fresh namespaces.
>
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> kui ~ $ racket measure-compile-time.rkt
> cpu time: 2244 real time: 2242 gc time: 172
> cpu time: 5244 real time: 6144 gc time: 516
> ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
>
> I assume that the reason for the difference is because the first
> version touches some namespace state that's used as a part of
> compilation, so that future compilations can reuse that state.

The state there is the instantiation of racket/base I believe.

> Question: is the first version vulnerable to a memory leak?  That is,
> let's say that I enforce all programs going through do-compilation to
> be in a hardcoded set of designated #langs.  Do I run the risk of
> exhausting memory?

All of the code that runs when the top-level of a module executes will
only happen once per namespace. So I suppose the answer is "it
depends". If you really need separate instantiations of the modules,
then you cannot have just one namespace.

Hope that's useful,
Robby


Posted on the users mailing list.