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 ;)
February 27th, 2010 at 09:09 PM
Hi,
I just want to warn you that your two examples are not exactly similar:
But tr also have some other capabilities, like swapping ‘i’ and ‘o’:
March 6th, 2010 at 11:43 AM
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>‘)
June 22nd, 2010 at 12:30 PM
Very nice post! Thank you, admin!