Skip to content

Instantly share code, notes, and snippets.

@swannodette
Created April 2, 2010 00:31
Show Gist options
  • Save swannodette/352580 to your computer and use it in GitHub Desktop.
Save swannodette/352580 to your computer and use it in GitHub Desktop.
(ns vector-math.core
(:import [javax.vecmath Vector2d]))
(defprotocol Vec2Math
(add [this other]))
(deftype vec2
[#^float x #^float y] :as this
Vec2Math
(add [other] (vec2. (+ x (.x #^vec2 other))
(+ y (.y #^vec2 other)))))
(def v1 (vec2 5.0 4.0))
;; ========== Create
;; ~50ms
(time
(dotimes [x 1000000]
[1.0 1.0]))
;; ~25ms
(time
(dotimes [x 1000000]
(vec2 1.0 1.0)))
;; ~18ms
(time
(dotimes [x 1000000]
(Vector2d. 1.0 1.0)))
;; ========== Access
;; ~28ms
(time
(let [v [1.0 1.0]]
(dotimes [x 1000000]
(do
(nth v 0)
(nth v 1)))))
;; ~30ms
(time
(let [v (vec2 1.0 1.0)]
(dotimes [x 1000000]
(do
(:x v)
(:y v)))))
;; ~27ms
(time
(let [v (Vector2d. 1.0 1.0)]
(dotimes [x 1000000]
(do
(.x v)
(.y v)))))
;; ========== Add
;; ~70ms
(time
(let [v1 [1.0 1.0]
v2 [0.5 0.5]]
(dotimes [x 1000000]
(map + v1 v2))))
;; ~27ms
(time
(let [v1 (vec2 1.0 1.0)
v2 (vec2 0.5 0.5)]
(dotimes [x 1000000]
(add v1 v2))))
;; ~7ms (mutable)
(time
(let [v1 (Vector2d. 1.0 1.0)
v2 (Vector2d. 0.5 0.5)]
(dotimes [x 1000000]
(.add v1 v2))))
;; ~21ms (immutable)
(time
(let [v1 (Vector2d. 1.0 1.0)
v2 (Vector2d. 0.5 0.5)]
(dotimes [x 1000000]
(Vector2d. (+ (.x v1) (.x v2))
(+ (.y v1) (.y v2))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment