DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
High-performance Ruby: Faster Symbol.to_s
Here's something that I found useful for shaving a few microseconds off. The performance gain ranges between 10% and 35%! YMMV.
Note: updated with suggestion by trans.
class Symbol
def to_s
@str_rep || (@str_rep = id2name.freeze)
end
end





Comments
jean-sébastien ney replied on Fri, 2007/03/30 - 6:30pm
Snippets Manager replied on Mon, 2012/05/07 - 2:26pm
Thomas Sawyer replied on Wed, 2006/08/16 - 12:21am
Snippets Manager replied on Mon, 2012/05/07 - 2:26pm
def to_s_fast @str_rep ||= to_s end def to_s_fast @str_rep = @str_rep || to_s end def to_s_fast instance_variable_set(:@str_rep, instance_variable_get(:@str_rep) || to_s) end def to_s_fast result = instance_variable_get(:str_rep) result = to_s if result.nil? instance_variable_set(:@str_rep) endWhat I'm trying to call out is that the instance_variable_set method may be invoked each time. Compare to these (again, roughly equivalent versions of the to_s_faster) method:def to_s_faster @str_rep || (@str_rep = to_s) end def to_s_faster return @str_rep unless @str_rep.nil? @str_rep = to_s end def to_s_faster instance_variable_get(:@str_rep) || instance_variable_set(:@str_rep, to_s) endCan anyone confirm or deny this? I use "@x ||= y" quite frequently and had assumed the variable assignment didn't take place if the LHS of the || was truthful.Snippets Manager replied on Mon, 2012/05/07 - 2:26pm
require 'benchmark' class Symbol def to_s_fast @str_rep ||= to_s end def to_s_faster @str_rep || (@str_rep = to_s) end end n = 1000000 Benchmark.bm do |x| x.report {n.times {:hello.to_s}} x.report {n.times {:hello.to_s_fast}} x.report {n.times {:hello.to_s_faster}} endSnippets Manager replied on Tue, 2006/08/15 - 7:37pm
class Symbol alias_method :__orig_to_s, :to_s def to_s @str_rep ||= __orig_to_s.freeze end end