From d0840e4a2332de4f6eb4959836de569b413723c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ludovic=20Court=C3=A8s?= <ludo@gnu.org>
Date: Wed, 30 Jan 2013 18:56:20 +0100
Subject: [PATCH] derivations: Memoize `read-derivation'.

* guix/derivations.scm (read-derivation): Rename to...
  (%read-derivation): ... this.
  (read-derivation): New procedure.
  This reduces the execution of "guix-build gdb" from 2.5s to 1.7s.
---
 guix/derivations.scm | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/guix/derivations.scm b/guix/derivations.scm
index 6f73534c3cf..60d57afa12a 100644
--- a/guix/derivations.scm
+++ b/guix/derivations.scm
@@ -155,9 +155,8 @@ (define (derivation-built? drv sub-drvs)
                      inputs)
                 (map derivation-input-sub-derivations inputs))))))
 
-(define (read-derivation drv-port)
-  "Read the derivation from DRV-PORT and return the corresponding
-<derivation> object."
+(define (%read-derivation drv-port)
+  ;; Actually read derivation from DRV-PORT.
 
   (define comma (string->symbol ","))
 
@@ -222,6 +221,20 @@ (define (make-input-drvs x)
        (loop (read drv-port)
              (cons (ununquote exp) result))))))
 
+(define read-derivation
+  (let ((cache (make-weak-value-hash-table 200)))
+    (lambda (drv-port)
+      "Read the derivation from DRV-PORT and return the corresponding
+<derivation> object."
+      ;; Memoize that operation because `%read-derivation' is quite expensive,
+      ;; and because the same argument is read more than 15 times on average
+      ;; during something like (package-derivation s gdb).
+      (let ((file (and=> (port-filename drv-port) basename)))
+        (or (and file (hash-ref cache file))
+            (let ((drv (%read-derivation drv-port)))
+              (hash-set! cache file drv)
+              drv))))))
+
 (define (write-derivation drv port)
   "Write the ATerm-like serialization of DRV to PORT.  See Section 2.4 of
 Eelco Dolstra's PhD dissertation for an overview of a previous version of
-- 
GitLab