Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created April 15, 2018 19:26
Show Gist options
  • Save havenwood/09d6d9389835339ce42e2ec359f36da3 to your computer and use it in GitHub Desktop.
Save havenwood/09d6d9389835339ce42e2ec359f36da3 to your computer and use it in GitHub Desktop.
Benchmarking a few solutions from the #ruby IRC channel
require 'benchmark/ips'
Benchmark.ips do |bm|
bm.report('String chars') { 64.to_s.chars.map(&:to_i).map(&:abs2).join.to_i }
bm.report('String digits') { 64.digits.map(&:abs2).reverse.join.to_i }
bm.report('Integer digits') { 64.digits.map.with_index { |n, i| n * n * 10 ** (i * 2) }.sum }
bm.compare!
end
ruby mark.rb
Warming up --------------------------------------
String chars 46.038k i/100ms
String digits 64.010k i/100ms
Integer digits 97.347k i/100ms
Calculating -------------------------------------
String chars 644.869k (± 3.4%) i/s - 3.223M in 5.003541s
String digits 869.585k (± 7.3%) i/s - 4.353M in 5.033445s
Integer digits 1.251M (± 4.2%) i/s - 6.328M in 5.067135s
Comparison:
Integer digits: 1250994.2 i/s
String digits: 869585.4 i/s - 1.44x slower
String chars: 644869.1 i/s - 1.94x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment