Symbol vs String performance in Ruby
A more interesting metric to this discussion is the use of strings versus symbols. Fortunately, these types of discussions can easily be solved by benchmarks:
Results under Ruby 1.8.6:
user system total real less no op String instanciation 9.050000 0.010000 9.060000 ( 9.057162) 5.921219 Symbol use 5.130000 0.000000 5.130000 ( 5.131844) 1.995901 new String#to_sym 14.550000 0.020000 14.570000 ( 14.567466) 11.431523 const String#to_sym 11.960000 0.010000 11.970000 ( 11.967217) 8.831274 String const lookup 6.350000 0.010000 6.360000 ( 6.358697) 3.222754 Symbol const lookup 6.400000 0.010000 6.410000 ( 6.416395) 3.280452 No op 3.130000 0.010000 3.140000 ( 3.135943) n/a
Results under Ruby 1.9.1:
user system total real less no op String instanciation 9.170000 0.010000 9.180000 ( 9.174451) 4.736163 Symbol use 4.920000 0.010000 4.930000 ( 4.930031) 0.491743 new String#to_sym 18.080000 0.030000 18.110000 ( 18.087386) 13.649098 const String#to_sym 13.940000 0.030000 13.970000 ( 13.954099) 9.515811 String const lookup 4.920000 0.000000 4.920000 ( 4.927497) 0.489209 Symbol const lookup 4.910000 0.020000 4.930000 ( 4.921151) 0.482863 No op 4.440000 0.000000 4.440000 ( 4.438288) n/a
What do these results mean? Well, first you need to subtract out the “no op” results from all the others, which I’ve added as a column above. We can now see that string instantiation takes about 90 nanoseconds, which means about 11000 string instantiations per millisecond. Are symbols faster? Considerably so. But the real lesson here is that these numbers are so small that no one in there right mind should spend time worrying about them.
So please, use symbols when you should use symbols, and otherwise use strings.