Create a gist now

Instantly share code, notes, and snippets.

Benchmarking in Crystal (for blogpost http://veelenga.com/benchmarking-in-crystal/)
require "benchmark"
puts ">> Array#[] vs Array#[]?"
arr = Array.new(1000, 1)
Benchmark.ips do |x|
x.report("Array#[]" ) { arr[500] }
x.report("Array#[]?") { arr[500]? }
end
puts ">> Interpolation vs Int32#to_s"
Benchmark.ips do |x|
x.report("Interpolation") { "#{100}" }
x.report("Int32#to_s") { 100.to_s }
end
puts ">> Interpolation vs Concatenation"
Benchmark.ips do |x|
x.report("Interpolation") { "#{100}:#{101}:#{102}" }
x.report("Concatenation") { 100.to_s + ":" + 101.to_s + ":" + 100.to_s}
end
puts ">> String#+ vs String.build"
n = 100_000
Benchmark.ips do |x|
x.report("String#+") do
s = ""
n.times do |i|
s += i.to_s
end
end
x.report("String.build") do
String.build do |s|
n.times do |i|
s << i
end
end
end
end
puts ">> Hash#fetch vs Hash#[] vs Hash#[]?"
HASH_WITH_SYMBOL = { fast: "crystal" }
HASH_WITH_STRING = { "fast" => "crystal" }
Benchmark.ips do |x|
x.report("Hash#[], symbol") { HASH_WITH_SYMBOL[:fast] }
x.report("Hash#[]?, symbol") { HASH_WITH_SYMBOL[:fast]? }
x.report("Hash#fetch, symbol") { HASH_WITH_SYMBOL.fetch(:fast) }
x.report("Hash#[], string") { HASH_WITH_STRING["fast"] }
x.report("Hash#[]?, string") { HASH_WITH_STRING["fast"]? }
x.report("Hash#fetch, string") { HASH_WITH_STRING.fetch("fast") }
end
$ crystal -v
Crystal 0.8.0 [124e1b1] (Sun Sep 20 17:47:29 UTC 2015)
$ crystal benchmark_test.cr --release
>> Array#[] vs Array#[]?
Array#[] 351.01M (± 2.15%) 1.12× slower
Array#[]? 392.77M (± 2.57%) fastest
>> Interpolation vs Int32#to_s
Interpolation 8.46M (± 6.70%) 4.29× slower
Int32#to_s 36.31M (± 4.14%) fastest
>> Interpolation vs Concatenation
Interpolation 6.15M (± 8.79%) fastest
Concatenation 4.61M (± 5.74%) 1.33× slower
>> String#+ vs String.build
String#+ 0.16 (± 0.00%) 1559.64× slower
String.build 249.87 (±12.73%) fastest
>> Hash#fetch vs Hash#[] vs Hash#[]?
Hash#[], symbol 130.06M (± 2.25%) 1.24× slower
Hash#[]?, symbol 161.42M (± 5.83%) fastest
Hash#fetch, symbol 125.95M (± 9.25%) 1.28× slower
Hash#[], string 88.75M (± 2.55%) 1.82× slower
Hash#[]?, string 97.72M (± 2.77%) 1.65× slower
Hash#fetch, string 88.41M (± 2.48%) 1.83× slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment