Re: Is this too inefficient?

From: Lars Thomas Hansen <lth_at_cs.uoregon.edu>
Date: Tue, 19 Dec 1995 16:24:39 -0800

>For an n-line file this does n mallocs each of which is an average of
>half the length of the file, and the number of characters copied in
>calls to string-append is half the square of the length of the file.
>Does this seem unreasonably inefficient to anyone else out there?

Yes.

I'd change it just a tad:

(define (port->string p)
  (unless (or (input-port? p) (input-string-port? p))
     (error "port->string: Bad port ~S" p))
  ;; Read all the lines of port and put them in a string
  (let loop ((res '()))
    (let ((line (read-line p))) ; aesthetic change only
      (if (eof-object? line)
          (apply string-append (reverse! res))
          (loop (cons "\n" (cons line res)))))))

This way you do only one allocation of the final string, if
string-append is at all reasonable.

(Note that the identity for string-append is "".)
(You can also avoid the reverse! but the savings will be close to nil.)

--lars
Received on Wed Dec 20 1995 - 01:28:37 CET

This archive was generated by hypermail 2.3.0 : Mon Jul 21 2014 - 19:38:59 CEST