Reputation: 4009
perhaps a simple question, but we are discussing about whether it better to use this snipper:
if %w(production staging).include?(Rails.env)
versus
if ["production","staging"].include?(Rails.env)
We just want to understand which is the most performant way, ignoring the sytax suggering from Ruby. From what I could on the web, the %w literal seems to be a shorthand to string.split on the provided whitespace string.
But which one is actually the fastest?
p.s : A source for the answer would be appreciated.
Upvotes: 2
Views: 406
Reputation: 66867
Here's what %w
and %W
do, taken directly from parse.y
(with ommissions):
case '%':
[snip]
switch (c) {
[snip]
case 'W':
lex_strterm = NEW_STRTERM(str_dword, term, paren);
do {c = nextc();} while (ISSPACE(c));
pushback(c);
return tWORDS_BEG;
case 'w':
lex_strterm = NEW_STRTERM(str_sword, term, paren);
do {c = nextc();} while (ISSPACE(c));
pushback(c);
return tQWORDS_BEG;
Considering it's implemented on the parser level, I wouldn't worry too much about the performance.
Upvotes: 7
Reputation: 89
I've done some test on my c2d:
ruby -e "10000000.times { ['one', 'two'].include?('two')}"
8.04s user 0.05s system 90% cpu 8.912 total
ruby -e "10000000.times { %w(one two).include?('two')}"
8.03s user 0.05s system 93% cpu 8.608 total
Upvotes: 3