[racket] Question about hash table efficiency

From: James Bergstra (james.bergstra at gmail.com)
Date: Thu Feb 14 13:16:47 EST 2013

Hi list, just discovered racket and having fun learning about scheme
again. Haven't used it since undergrad. Thanks!

I was wondering about the efficiency of hash-update vs. hash-set and
hash-ref. I thought the former would be faster, otherwise why have it?
A little benchmark script reveals the same surprising result as my
actual application though:

"""
#lang racket

;; warm-up
(time (void
 (for/fold ([table (make-immutable-hasheq '())])
  ([ii (in-range 100000)])
  (hash-update table (modulo ii 100) add1 ii))))

;; update
(newline)
(time (void
 (for/fold ([table (make-immutable-hasheq '())])
  ([ii (in-range 100000)])
  (hash-update table (modulo ii 100) add1 ii))))

;; set/ref
(newline)
(time (void
 (for/fold ([table (make-immutable-hasheq '())])
  ([ii (in-range 100000)])
  (hash-set table (modulo ii 100) (add1 (hash-ref table (modulo ii 100) ii))))))

"""

This prints out:

cpu time: 112 real time: 114 gc time: 32

cpu time: 80 real time: 82 gc time: 0

cpu time: 76 real time: 75 gc time: 4


My original application used mutable hash tables and the same effect
was observed (if not more dramatically). Any thoughts on why the
update form is slower? I'm running this in Racket v5.1.1.

- James

Posted on the users mailing list.