Escape Analysis - Examples (Scheme)

Examples (Scheme)

In the following example, the vector p does not escape into g, so it can be allocated on the stack and then removed from the stack before calling g.

(define (f x) (let ((p (make-vector 10000))) (fill-vector-with-good-stuff p) (g (vector-ref p 7023))))

If, however, we had

(define (f x) (let ((p (make-vector 10000))) (fill-vector-with-good-stuff p) (g p)))

then either p would need to be allocated on the heap or (if g is known to the compiler when f is compiled, and behaves well) allocated on the stack in such a fashion that it can remain in place when g is called.

If continuations are used to implement exception-like control structures, escape analysis can often detect this to avoid having to actually allocate a continuation and copy the call stack into it. For example, in

;;Reads scheme objects entered by the user. If all of them are numbers, ;;returns a list containing all of them in order. If the user enters one that ;;is not a number, immediately returns #f. (define (getnumlist) (call/cc (lambda (continuation) (define (get-numbers) (let ((next-object (read))) (cond ((eof-object? next-object) ') ((number? next-object) (cons next-object (get-numbers))) (else (continuation #f))))) (get-numbers))))

escape analysis will determine that the continuation captured by call/cc doesn't escape, so no continuation structure needs to be allocated, and invoking the continuation by calling continuation can be implemented by truncating the stack.

Read more about this topic:  Escape Analysis

Famous quotes containing the word examples:

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)