String#tr vs String#gsub

January 21st, 2010

I’ve always used gsub method for all simle string replacements. But recently I found tr method. It’s not so powerful, as it doesn’t support regexps, but in most common cases can do the same work as gsub.

To check difference in execution time, I did simple benchmark:
Benchmark.bm(10) do |b|
  b.report("tr")   { 1.upto(10000){ "heloo knapo".tr('o','i') } }
  b.report("gsub") { 1.upto(10000){ "heloo knapo".gsub('o','i') } }
end

And the result surprised me a little bit. I supposed that gsub is slower, but did not that more than 2 times:

                user     system      total        real
tr          0.030000   0.000000   0.030000 (  0.047241)
gsub        0.070000   0.010000   0.080000 (  0.109662)

So now, I have clear choice with simple string replacements – especially that tr is shorter ;)

3 Responses to “String#tr vs String#gsub”

  1. Bruno Michel Says:

    Hi,

    I just want to warn you that your two examples are not exactly similar:

    “heloo knapo”.tr(‘o’,’ik’) => “helii knapi” “heloo knapo”.gsub(‘o’,’ik’) => “helikik knapik”

    But tr also have some other capabilities, like swapping ‘i’ and ‘o’:

    “heloo knapi”.tr(‘io’,’oi’) => “helii knapo”

  2. knapo Says:

    Thanks Bruno for noticing my mistake, you’re right. Of course, I agree that they work different way, but in simple cases (which are most common) they have the same results. Both can do the things, which would be very tricky do with the second one (as you presented):

    e.g. “hello”.tr(‘a-y’, ‘b-z’) “hello”.gsub(/([aeiou])/, ‘<\1>‘)

  3. adepev Says:

    Very nice post! Thank you, admin!

Leave a Reply