Created
March 16, 2012 05:40
-
-
Save amasses/2048697 to your computer and use it in GitHub Desktop.
Benchmark of different way to make a name string from first_name and last_name
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
# Note: I realize this is trivial, but this is a pattern I use a lot (name from first/last) so I was | |
# curious as to which method was quicker, and if perhaps I've been doing it wrong...? Run on 1.9.3 | |
require 'benchmark' | |
first_name = "john" | |
last_name = "smith" | |
i = 1000000 | |
# Reopen string to add the blank? method | |
class String | |
def blank? | |
self !~ /[^[:space:]]/ | |
end | |
end | |
Benchmark.bm(7) do |x| | |
x.report("string: ") { i.times { "#{first_name} #{last_name}" }} | |
x.report("array join: ") { i.times { [first_name, last_name].join(" ") }} | |
x.report("array join with rejection: ") { i.times { [' ', last_name].reject(&:blank?).join(" ") }} | |
x.report("concat: ") { i.times { first_name + " " + last_name }} | |
x.report("sprintf: ") { i.times { sprintf("%s %s", first_name, last_name) }} | |
end |
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
user system total real | |
string: 0.680000 0.000000 0.680000 ( 0.677926) | |
array join: 1.190000 0.030000 1.220000 ( 1.245561) | |
array join with rejection: 5.510000 0.020000 5.530000 ( 5.531430) | |
concat: 0.680000 0.000000 0.680000 ( 0.683626) | |
sprintf: 1.340000 0.010000 1.350000 ( 1.346253) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment