Note: updated with suggestion by trans.
class Symbol def to_s @str_rep || (@str_rep = id2name.freeze) end end
12378 users tagging and storing useful source code snippets
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
class Symbol def to_s @str_rep || (@str_rep = id2name.freeze) end end
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}} end
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) end
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) end
You need to create an account or log in to post comments to this site.