From: Joel VanderWerf Date: 2007-09-07T00:05:05+09:00 Subject: Re: Symbols and frozen strings Brian Candler wrote: > I just had a thought. > > One of the problems with using strings as hash keys is that every time you > refer to them, you create a throw-away garbage string: > > params["id"] > ^ > +-- temporary string, needs to be garbage collected Setting aside the question of freezing, why can't ruby share string data for all strings generated from the same symbol? And in that case you could do the following to avoid garbage: params[:id.to_s] (Or ruby could even look up the literal "id" in the symbol table and do this for you.) This code shows some of the cases in which ruby does and does not share string contents: def show_vmsize GC.start puts `ps -o vsz #$$`[/\d+/] end s = "a"*1000 sym = s.to_sym show_vmsize # 8712 # ruby apparently does not share storage for strings derived # from the same symbol: strs1 = (0..10_000).map do sym.to_s end show_vmsize # 18488 # ruby does share storage for string ops: strs2 = (0..10_000).map do s[0..-1] end show_vmsize # 18616 strs3 = (0..10_000).map do s.dup end show_vmsize # 18616 -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407