-
-
Save takikawa/4046452 to your computer and use it in GitHub Desktop.
Why is a simple contract so much slower than a check?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(define (f/raw x) | |
#t) | |
(define (f/checked x) | |
(unless (exact-nonnegative-integer? x) | |
(error 'f/checked "blah blah")) | |
#t) | |
(define f/chaperoned | |
(chaperone-procedure | |
f/raw | |
(λ (x) (contract exact-nonnegative-integer? x 'pos 'neg)))) | |
;; using contract-out | |
(module f racket | |
(provide | |
(contract-out | |
[f/from-module (-> exact-nonnegative-integer? any)])) | |
(define (f/from-module x) #t)) | |
(require 'f) | |
(define/contract (f/contracted x) | |
(exact-nonnegative-integer? . -> . any) | |
#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/chaperoned) | |
(bench f/from-module) | |
#| | |
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 | |
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? | |
|# |
@samth Running the above I get:
f/raw: cpu time: 4 real time: 4 gc time: 0
f/checked: cpu time: 6 real time: 6 gc time: 0
f/contracted: cpu time: 1288 real time: 1327 gc time: 341
f/raw: cpu time: 204 real time: 211 gc time: 66 <-- really f/chaperone, not f/raw
f/from-module: cpu time: 22 real time: 22 gc time: 0
@samth @takikawa
FWIW I took my original gist further: https://gist.github.com/4049108
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And the chaperone performance results?