Skip to content

Instantly share code, notes, and snippets.

@lucatironi
Created August 6, 2016 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucatironi/47512da30831b9b316f7123b764fab33 to your computer and use it in GitHub Desktop.
Save lucatironi/47512da30831b9b316f7123b764fab33 to your computer and use it in GitHub Desktop.
Scraps
require 'benchmark/ips'
def simple_fib(n)
return n if [0, 1].include?(n)
simple_fib(n - 1) + simple_fib(n - 2)
end
def rec_fib(n)
rec = -> (a, b, n) { n == 0 ? a : rec.call(b, a + b, n - 1) }
rec.call(0, 1, n)
end
upto = 30
Benchmark.ips do |x|
x.report("simple_fib") { (0..upto).map { |i| simple_fib(i) } }
x.report("rec_fib") { (0..upto).map { |i| rec_fib(i) } }
x.compare!
end
(1..upto).each do |n|
puts "#{n}: #{rec_fib(n)}"
end
require 'oj'
require 'json'
require 'pp'
require 'benchmark/ips'
hash = {
foo: 'bar',
baz: 100,
baz: {
buzz: 123,
fizz: 'hello world'
}
}
data = 100_000.times.reduce({}) { |h, i| h[i] = hash; h }.freeze
Benchmark.ips do |x|
x.report("Oj.dump") { Oj.dump(data) }
x.report("to_json") { data.to_json }
x.compare!
end
def retrieve(path, hash)
remainder = hash.fetch(path.shift, nil)
remainder.is_a?(Hash) ? retrieve(path, remainder) : remainder
end
path = [:foo, :bar, :baz]
hash = { foo: { bar: { baz: 123 } } }
puts "path: #{path}"
puts "hash: #{hash}"
puts "result: #{retrieve(path, hash)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment