Hi,

On Thu, Sep 25, 2025 at 3:55 PM Dr. Arne Babenhauserheide
<[email protected]> wrote:
>
> Hi,
>
> While optimizing an implementation of levenshtein distance, I found that
> (min ...) took up a significant part of the profile (16%), so I tried
> replacing it with a simple implementation in Scheme. That worked out
> surprisingly well (shaved off about 25% of the total runtime) and when I
> benchmarked it directly it turned out to be between 1.5 and 3 times
> faster than the min in numbers.c.

FWIW, here's the implementation in Hoot that is simpler:
https://codeberg.org/spritely/hoot/src/branch/main/lib/hoot/numbers.scm#L485

> Would it be a good idea to move min and max from C to Scheme? And what
> would be needed?

Yes, it would be a good idea. I'd prefer to use an implementation that
produces inlined code when the arity is known at compile time so that
the partial eval and type inference passes can optimize it. As a
trivial example, (lambda () (min 42 99)) should optimize to just
(lambda () 42). However, case-lambda based implementations of min/max
don't produce the code I'd like to see. A macro with identifier syntax
for the pass-by-reference case does the trick, though. Something along
these lines:

(define %min
  (case-lambda
    ((x) x)
    ((x y) (if (< x y) x y))
    ((x y . z) (apply %min (%min x y) z))))

(define-syntax min
  (lambda (stx)
    (syntax-case stx ()
      (id
       (identifier? #'id)
       #'%min)
      ((_ x) #'x)
      ((_ x y)
       #'(let ((x* x)
               (y* y))
           (if (< x* y*) x* y*)))
      ((_ x y ...)
       #'(let ((x* x)
               (m (min y ...)))
           (if (< x* m) x* m))))))

(define %max
  (case-lambda
    ((x) x)
    ((x y) (if (> x y) x y))
    ((x y . z) (apply %max (%max x y) z))))

(define-syntax max
  (lambda (stx)
    (syntax-case stx ()
      (id
       (identifier? #'id)
       #'%max)
      ((_ x) #'x)
      ((_ x y)
       #'(let ((x* x)
               (y* y))
           (if (> x* y*) x* y*)))
      ((_ x y ...)
       #'(let ((x* x)
               (m (max y ...)))
           (if (> x* m) x* m))))))

- Dave

Reply via email to