SHARE
TWEET

Untitled

a guest Jan 12th, 2017 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def random_bytes
  2.   100_000 + rand(128849018880)
  3. end
  4.  
  5. require 'benchmark/ips'
  6.  
  7. file_sizes = 350_000.times.map { random_bytes }
  8. MEGA_BYTE = 1048576.0
  9.  
  10. Benchmark.ips do |x|
  11.   x.time = 5
  12.   x.warmup = 2
  13.  
  14.   x.report("devide first") {
  15.     file_sizes.map{|a| a / MEGA_BYTE }.inject(&:+)
  16.   }
  17.  
  18.   x.report("devide last") {
  19.     file_sizes.inject(&:+) / MEGA_BYTE
  20.   }
  21.  
  22.   x.compare!
  23. end
  24.  
  25.  
  26. HASH = Hash[500.times.map { [random_bytes, random_bytes] } ]
  27.  
  28. Benchmark.ips do |x|
  29.   x.time = 5
  30.   x.warmup = 2
  31.  
  32.   x.report("inject assign") {
  33.     HASH.inject({}) do |memo, (k, v)|
  34.       memo[k] = v
  35.       memo
  36.     end
  37.   }
  38.  
  39.   x.report("inject merge") {
  40.     HASH.inject({}) do |memo, (k, v)|
  41.       memo.merge({k => v})
  42.     end
  43.   }
  44.  
  45.   x.report("inject merge!") {
  46.     HASH.inject({}) do |memo, (k, v)|
  47.       memo.merge!({k => v})
  48.     end
  49.   }
  50.  
  51.   x.report("with_object assign") {
  52.     HASH.each_with_object({}) do |(k, v), memo|
  53.       memo[k] = v
  54.     end
  55.   }
  56.  
  57.   x.report("with_object merge") {
  58.     HASH.each_with_object({}) do |(k, v), memo|
  59.       memo.merge(k => v)
  60.     end
  61.   }
  62.  
  63.   x.report("with_object merge!") {
  64.     HASH.each_with_object({}) do |(k, v), memo|
  65.       memo.merge!(k => v)
  66.     end
  67.   }
  68.  
  69.   x.compare!
  70. end
RAW Paste Data
Top