Created
August 6, 2016 09:37
-
-
Save lucatironi/47512da30831b9b316f7123b764fab33 to your computer and use it in GitHub Desktop.
Scraps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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