Skip to content

Instantly share code, notes, and snippets.

@greghendershott
Created November 9, 2012 15:04
Show Gist options
  • Save greghendershott/4046196 to your computer and use it in GitHub Desktop.
Save greghendershott/4046196 to your computer and use it in GitHub Desktop.
Why is a simple contract so much slower than a check?
#lang racket
(define (f/raw x)
#t)
(define (f/checked x)
(unless (exact-nonnegative-integer? x)
(error 'f/checked "blah blah"))
#t)
(define/contract (f/contracted x)
(exact-nonnegative-integer? . -> . any)
#t)
(define f/chaperoned
(chaperone-procedure
f/raw
(λ (x) (contract exact-nonnegative-integer? x 'pos 'neg))))
(define (f/checked-w/contract x) ;use contact without "chaperone"
(unless ((and/c (not/c negative?) integer?) x)
(error 'f/checked-w/contract "blah blah"))
#t)
(define f/checked-w/contract2 ;avoid recreating the contract on every call
(let ([chk? (and/c (not/c negative?) integer?)])
(lambda (x)
(unless (chk? x)
(error 'f/checked-w/contract2 "blah blah"))
#t)))
(define count 100000)
(define-syntax-rule (bench func)
(begin
(display (object-name func)) (display ": ")
(time (for ([i (in-range count)])
(func i)))
(void)))
(version)
(bench f/raw)
(bench f/checked)
(bench f/contracted)
(bench f/checked-w/contract)
(bench f/checked-w/contract2)
(displayln "The following is really f/chapareoned, not f/raw:")
(bench f/chaperoned)
#|
Example output:
"5.3"
cpu time real time gc time
f/raw: 4 4 0
f/checked: 6 6 0
f/contracted: 1166 1197 211
f/checked-w/contract: 319 336 77
f/checked-w/contract2: 49 50 0
f/chaperoned: 165 169 19
Naively I would expect the simple contract to result in code
not _too_ much more complicated or slower than the manual check.
1. Why not?
2. Could simple contracts be (nearly) as fast as manual checks?
To get the declarative convenince and clarity of contracts, without
so much overhead?
|#
@greghendershott
Copy link
Author

p.s. I suppose one answer could be, "Use Typed Racket instead". I'm warming up to trying TR soon. Even so, that doesn't really answer the question. Plus, it's not really a matter of "contracts vs. TR". IIUC TR uses contracts for interoperability with untyped modules. A simple contract like above seems like exactly the sort of contract TR would use. If 200X faster, would benefit use of TR, no?

@greghendershott
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment