From: Kent Dahl Date: 2002-10-17T17:46:33+09:00 Subject: Re: Strings or symbols? Gavin Sinclair wrote: > Given all this, I would use Strings if I were you. For plain indices that > don't really need to be interpreted outside the hash, I use symbols. I think > symbols are more efficient, too (but probably not if you're converting them to > strings all the time). Or converting strings to symbols, if I understood the OP correctly :-) As I understand it, the potential gain in using symbols, is depending on how the hash value is computed. Since a symbol is an internalized string, it could potentially be quicker. I tried a quick and dirty profiling test. Not surprising, using symbols are quicker than using strings. Naturally stringifying a symbol or interning a string before hash lookup is slower than either of the above. (Quite surprising to me, they both appear to be approximately equal in time usage.) So it is a matter of weighing how many times you guess you will be looking up with symbols directly versus when you need to internalize a string. If the script sets the variables from the CGI once (requiring an intern to get symbol), but access it in the script elsewhere using symbol a lot of times, symbols would be the way to go. (CGI communication usually is slow as heck anyway, since you probably have a user infront of a HTML form being the slowest link :-) require 'profile' N = 10000 H = { :abba => ':A', 'abba' => 'A' } def time_strings N.times do |i| H['abba'] end end def time_string_interned N.times do |i| H['abba'.intern] end end def time_symbols N.times do |i| H[:abba] end end def time_symbols_stringified N.times do |i| H[:abba.to_s] end end time_strings time_symbols time_string_interned time_symbols_stringified [kentda@v052a ruby]$ /usr/local/bin/ruby symbol.rb % cumulative self self total time seconds seconds calls ms/call ms/call name 63.43 7.13 7.13 4 1782.50 2810.00 Integer#times 14.41 8.75 1.62 40000 0.04 0.04 Hash#[] 9.07 9.77 1.02 30004 0.03 0.03 String#allocate 8.99 10.78 1.01 10000 0.10 0.13 Symbol#to_s 4.09 11.24 0.46 10000 0.05 0.05 String#intern 0.00 11.24 0.00 1 0.00 11240.00 #toplevel 0.00 11.24 0.00 1 0.00 1390.00 Object#time_symbols 0.00 11.24 0.00 1 0.00 3680.00 Object#time_symbols_stringified 0.00 11.24 0.00 4 0.00 0.00 Module#method_added 0.00 11.24 0.00 1 0.00 2520.00 Object#time_strings 0.00 11.24 0.00 1 0.00 3650.00 Object#time_string_interned [kentda@v052a ruby]$ /usr/local/bin/ruby --version ruby 1.7.2 (2002-07-13) [i686-linux] -- (\[ Kent Dahl ]/)_ _~_ __[ http://www.stud.ntnu.no/~kentda/ ]___/~ ))\_student_/(( \__d L b__/ NTNU - graduate engineering - 5. year ) ( \__\_�|�_/__/ ) _)Industrial economics and technological management( \____/_�_\____/ (____engineering.discipline_=_Computer::Technology___)