Skip to content

Instantly share code, notes, and snippets.

@goromlagche
Created August 8, 2019 08:21
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 goromlagche/7cf007a61522c3005c99890d1d435af1 to your computer and use it in GitHub Desktop.
Save goromlagche/7cf007a61522c3005c99890d1d435af1 to your computer and use it in GitHub Desktop.
compare between first, range and active_supports truncate
require 'benchmark/ips'
require 'active_support/all'
STRING = 'Once upon a time in a world far far away'
def use_truncate
STRING.truncate(27)
end
def use_first
STRING.first(27)
end
def use_range
STRING[0...27]
end
Benchmark.ips do |x|
x.report('truncate') { use_truncate }
x.report('first') { use_first }
x.report('range') { use_range }
x.compare!
end
=begin
Warming up --------------------------------------
truncate 53.883k i/100ms
first 78.153k i/100ms
range 99.488k i/100ms
Calculating -------------------------------------
truncate 760.175k (± 5.5%) i/s - 3.826M in 5.049342s
first 1.162M (±12.1%) i/s - 5.705M in 5.038751s
range 1.719M (± 6.5%) i/s - 8.556M in 5.001056s
Comparison:
range: 1718907.6 i/s
first: 1162328.6 i/s - 1.48x slower
truncate: 760175.0 i/s - 2.26x slower
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment