Performance and Profiling in Racket | Schema Programming Part 30
Racket is generally fast (JIT-compiled), but you can make it faster. The first step is always measurement.
Advertisement
The Profiler
Don't guess where your code is slow. Use the profile library.
#lang racket
(require profile)
(define (fib n)
(if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
(profile (fib 30))
This prints a report showing which functions took the most time and how many times they were called.
Typed Racket (Again)
We mentioned Typed Racket in Part 13. Aside from safety, it is also the primary performance tool. The compiler can use type information to unbox numbers and inline operations.
Fixnum/Flonum Optimizations
If you are doing heavy math in standard Racket and need raw speed, use specific operations for "Fixnums" (small integers) and "Flonums" (floating point numbers).
(require racket/fixnum)
(fx+ 10 20) ; Faster than + because it skips overflow checks
Warning: These operations are unsafe if you overflow!
Vector vs List
Lists are great for recursion, but they have O(N) access time. For performance-critical code, use Vector for O(1) access.
(define v (vector 1 2 3))
(vector-ref v 2) ; Instant
Advertisement
Summary
- Profile first.
- Algorithm change second (loops vs recursion).
- Data structure change third (Vector vs List).
- Typed Racket / Fixnum ops last.
Which library helps you identify which parts of your code are running slowly?
Md Nasim Sheikh
Software Developer at softexForge