Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. require 'benchmark/ips'
  2.  
  3. # hash.size # 1000
  4. # hash.values.flatten.size # 500500
  5. def a_big_hash
  6. {}.tap do |h|
  7. 1.upto(1000) { |i| h[i.to_s.to_sym] = 1.upto(i).to_a }
  8. end
  9. end
  10.  
  11. class Hash
  12. # map to_h
  13. def hmap1 &block
  14. self.map(&block).to_h
  15. end
  16.  
  17. # tap each
  18. def hmap2 &block
  19. {}.tap do |h|
  20. each do |i|
  21. k, v = block.call(i)
  22. h[k] = v
  23. end
  24. end
  25. end
  26.  
  27. # reduce
  28. def hmap3 &block
  29. reduce({}) do |acc, i|
  30. pair = block.call(i)
  31. acc.merge({pair[0] => pair[1].size})
  32. end
  33. end
  34.  
  35. # map reduce
  36. def hmap4 &block
  37. map { |i|
  38. k, v = block.call(i)
  39. {k => v}
  40. }.reduce(:merge)
  41. end
  42.  
  43. # brackets splat flat_map
  44. def hmap5 &block
  45. Hash[*flat_map(&block)]
  46. end
  47. end
  48.  
  49.  
  50. Benchmark.ips do |bm|
  51. bm.time = 10
  52. bm.warmup = 5
  53.  
  54. hash = a_big_hash.freeze # nothing should attempt to mutate hash
  55. counter = proc { |k, v| [k, v.size] }
  56.  
  57. bm.report 'map to_h' do
  58. hash.hmap1 &counter
  59. end
  60.  
  61. bm.report 'tap each' do
  62. hash.hmap2 &counter
  63. end
  64.  
  65. bm.report 'reduce' do
  66. hash.hmap3 &counter
  67. end
  68.  
  69. bm.report 'map reduce' do
  70. hash.hmap4 &counter
  71. end
  72.  
  73. bm.report '[] splat flat_map' do
  74. hash.hmap5 &counter
  75. end
  76.  
  77. bm.compare!
  78. end
  79.  
  80.  
  81. # Calculating -------------------------------------
  82. # map to_h 110.000 i/100ms
  83. # tap each 88.000 i/100ms
  84. # reduce 1.000 i/100ms
  85. # map reduce 1.000 i/100ms
  86. # [] splat flat_map 116.000 i/100ms
  87. # -------------------------------------------------
  88. # map to_h 1.374k (±19.7%) i/s - 13.310k
  89. # tap each 926.439 (±25.7%) i/s - 8.536k
  90. # reduce 3.397 (±29.4%) i/s - 33.000
  91. # map reduce 3.596 (±27.8%) i/s - 35.000
  92. # [] splat flat_map 1.246k (±19.5%) i/s - 11.948k
  93.  
  94. # Comparison:
  95. # map to_h: 1373.5 i/s
  96. # [] splat flat_map: 1245.5 i/s - 1.10x slower
  97. # tap each: 926.4 i/s - 1.48x slower
  98. # map reduce: 3.6 i/s - 381.94x slower
  99. # reduce: 3.4 i/s - 404.28x slower
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement