Created
September 20, 2010 19:35
-
-
Save stevenchanin/588512 to your computer and use it in GitHub Desktop.
Benchmarking Data & Functional Implementations of List
This file contains 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
#This is the code underneath the blog post: | |
#http://stevechanin.blogspot.com/2010/09/benchmarking-functional-vs-data-based.html | |
List = Struct.new(:head, :tail) | |
Cons = ->(h,t) { List.new(h,t) } | |
Car = ->(list) { list.head } | |
Cdr = ->(list) { list.tail } | |
#[1, [2, 3], 4, 5] | |
lst = Cons.(1, Cons.(Cons.(2, Cons.(3, nil)), Cons.(4, Cons.(5,nil)))) | |
raise "Problem with Car and Cdr" unless Car.(Cdr.(Cdr.(l))) == 4 | |
f_Cons = ->(h,t) { ->(s) { (s==:h) ? h : t } } | |
f_Car = ->(list) { list.(:h) } | |
f_Cdr = ->(list) { list.(:t) } | |
f_lst = f_Cons.(1, f_Cons.(f_Cons.(2, f_Cons.(3, nil)), f_Cons.(4, f_Cons.(5,nil)))) | |
raise "Problem with f_Car and f_Cdr" unless f_Car.(f_Cdr.(f_Cdr.(f_lst))) == 4 | |
class List2 | |
attr_reader :car, :cdr | |
def initialize(car, cdr) | |
@car = car | |
@cdr = cdr | |
end | |
def self.Cons(car, cdr) | |
List2.new(car, cdr) | |
end | |
end | |
c_lst = List2.Cons(1, List2.Cons(List2.Cons(2, List2.Cons(3, nil)), List2.Cons(4, List2.Cons(5,nil)))) | |
raise "Problem with List2.car and List2.cdr" unless c_lst.cdr.cdr.car | |
require 'benchmark' | |
c = 100_000 | |
n = 5_000_000 | |
#this benchmarks creates and extracting the "4" from (1, (2, 3), 4, 5) | |
Benchmark.bm do |rpt| | |
rpt.report("List Create") { c.times do; Cons.(1, Cons.(Cons.(2, Cons.(3, nil)), Cons.(4, Cons.(5,nil)))); end;} | |
rpt.report("List Extract") { n.times do; Car.(Cdr.(Cdr.(lst))); end;} | |
rpt.report("Func Create") { c.times do; f_Cons.(1, f_Cons.(f_Cons.(2, f_Cons.(3, nil)), f_Cons.(4, f_Cons.(5,nil)))); end;} | |
rpt.report("Func Extract") { n.times do; f_Car.(f_Cdr.(f_Cdr.(f_lst))); end;} | |
rpt.report("Class Create") { c.times do; List2.Cons(1, List2.Cons(List2.Cons(2, List2.Cons(3, nil)), List2.Cons(4, List2.Cons(5,nil)))); end;} | |
rpt.report("Class Extract") { n.times do; c_lst.cdr.cdr.car; end;} | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment