Skip to content

Instantly share code, notes, and snippets.

@metaskills
Created December 16, 2010 14:44
Show Gist options
  • Save metaskills/743466 to your computer and use it in GitHub Desktop.
Save metaskills/743466 to your computer and use it in GitHub Desktop.
which_is_easier_to_read.rb
%w(id foo under_score bar batz_score)
["id", "foo", "under_score", "bar", "batz_score"]
[:id, :foo, :under_score, :bar, :batz_score]
Author: Ken Collins
Date: December 16, 2010
Summary: Arrays
System Information
------------------
Operating System: Mac OS X 10.6.5 (10H574)
CPU: Quad-Core Intel Xeon 2.66 GHz
Processor Count: 4
Memory: 8 GB
ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10.4.0]
"literal w/symbols" is up to 28% faster over 1,000 repetitions
--------------------------------------------------------------
literal w/symbols 0.00223708152770996 secs Fastest
literal w/strings 0.00305581092834473 secs 26% Slower
%w() 0.00312900543212891 secs 28% Slower
require 'rubygems'
require 'bench_press'
extend BenchPress
author 'Ken Collins'
summary 'Arrays'
reps 1_000
measure "%w()" do
%w(id foo under_score bar batz_score).each { |attrib| }
end
measure "literal w/strings" do
["id", "foo", "under_score", "bar", "batz_score"].each { |attrib| }
end
measure "literal w/symbols" do
[:id, :foo, :under_score, :bar, :batz_score].each { |attrib| }
end
@metaskills
Copy link
Author

As a previous designer and typographer, I found out a few key things in regards to reading text. One was that UPPER CASE IS NOT THE WAY TO GET ATTENTION or to see a heading better. Why? Well the eye when scanning text looks for predefined word shapes to recognize them quickly. So using a correct sentence/mix-case will allow the eye to read it better and more quickly.

So just like I hate all upper case, I also hate %w{...} array literals, especially when used with words that have underscores. It is very hard for the eye to distinguish the space delimiter and quickly see what is going on. I submit that when dealing with array literals that the symbol syntax is far cleaner, saves memory and more important is easy on the eye to read. It is especially useful for attribute assignment too for ActiveRecord objects because these symbols are constant and are likely used in the app elsewhere, so the cry of symbols are not GC'ed are moot too!

The most important aspect is legibility!

@kleb
Copy link

kleb commented Dec 16, 2010

I seem to recall a rant by Ara Howard about use of symbols being evil.

@josephholsten
Copy link

String#to_sym for arbitrary strings is evil because it adds to the symbol table, so it can cause your process to grow as it runs. If you're typing %w(foo bar), than these aren't arbitrary strings, they're important to your code. So you'll probably be using them again. Thus, this is probably not an evil use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment