Advertisement
Guest User

Untitled

a guest
May 4th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. (defn compile-get-in [path]
  2. (let [f (reduce
  3. (fn [acc k]
  4. (fn [m] (get (acc m) k)))
  5. identity path)]
  6. (fn [m]
  7. (f m))))
  8.  
  9. (let [m {:a {:b 1}}]
  10. (time (dotimes [i 100000]
  11. (get-in m [:a :b]))))
  12. ;; => "Elapsed time: 11.897221 msecs"
  13.  
  14. (let [m {:a {:b 1}}
  15. compiled-get-in-fn (compile-get-in [:a :b])]
  16. (time (dotimes [i 100000]
  17. (compiled-get-in-fn m))))
  18. ;; => "Elapsed time: 5.3357 msecs"
  19.  
  20. ;; Significantly more efficient for larger paths and matching maps
  21. (let [m {:a {:b {:c {:d 1}}}},
  22. compiled-get-in-fn (compile-get-in [:a :b :c :d])]
  23. (time (dotimes [i 100000]
  24. (compiled-get-in-fn m))))
  25. ;; => "Elapsed time: 8.376878 msecs"
  26.  
  27. (let [m {:a {:b {:c {:d 1}}}}]
  28. (time (dotimes [i 100000]
  29. (get-in m [:a :b :c :d]))))
  30. ;; => "Elapsed time: 14.608494 msecs"
  31.  
  32. ;; Benefit seems to get smaller with an increasing path size and no match
  33. ;; One option would be to terminate the loop premature when sentinel value has been found
  34.  
  35. (let [m {:a {:b 1}}]
  36. (time (dotimes [i 100000]
  37. (get-in m [:a :b :c :d]))))
  38. ;; => "Elapsed time: 22.612878 msecs"
  39.  
  40. (let [m {:a {:b 1}},
  41. compiled-get-in-fn (compile-get-in [:a :b :c :d])]
  42. (time (dotimes [i 100000]
  43. (compiled-get-in-fn m))))
  44. ;; => "Elapsed time: 18.415237 msecs"
  45.  
  46.  
  47. ;; Adjusted version for no matching paths?
  48.  
  49. (defn compile-get-in [path]
  50. (let [f (reduce
  51. (fn [acc k]
  52. (fn [m] (when-let [m0 (acc m)]
  53. (get m0 k))))
  54. identity path)]
  55. (fn [m]
  56. (f m))))
  57.  
  58. (let [m {:a {:b 1}},
  59. compiled-get-in-fn (compile-get-in [:a :b :c :d])]
  60. (time (dotimes [i 100000]
  61. (compiled-get-in-fn m))))
  62. ;; => "Elapsed time: 12.751598 msecs"
  63.  
  64. ;; Matched version is faster?
  65. (let [m {:a {:b {:c {:d 1}}}},
  66. compiled-get-in-fn (compile-get-in [:a :b :c :d])]
  67. (time (dotimes [i 100000]
  68. (compiled-get-in-fn m))))
  69. ;; => "Elapsed time: 7.738589 msecs"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement