"Cameron McBride" <cameron.mcbride / gmail.com> schrieb im Newsbeitrag
news:dcedf5e204071320562e0ad096 / mail.gmail.com...
> > What possible benefit is there to typing split(" ") vs. split(/\s/)?
> > One saved character (but two shift key presses!)?
>
> they are not the same:
>
> irb(main):001:0> s = "this is\tfun \tno?"
> => ["this", "is", "fun", "no?"]
> irb(main):003:0> s.split(" ")
> => "this is\tfun \tno?"
> irb(main):002:0> s.split(/\s/)
> => ["this", "is", "fun", "", "no?"]

I'd rather compare split(" ") to split(/\s+/), which is what I use when I
need this functionality.  IMHO regular expressions are better suited to
this task anyway.  And they are faster:

def test1(s) s.split ' ' end

def test2(s) s.split /\s+/ end

foo = (1..100).to_a.join " "

1000.times { test1 foo }
1000.times { test2 foo }

Yields

11:12:47 [source]: /c/temp/split-perf.rb
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ms/call  ms/call  name
 61.58     0.62      0.62     2000     0.31     0.31  String#split
 15.37     0.78      0.16     1000     0.16     0.39  Object#test1
 13.79     0.92      0.14        2    70.00   507.50  Integer#times
  9.26     1.02      0.09     1000     0.09     0.48  Object#test2
  3.05     1.05      0.03        1    31.00    31.00
Profiler__.start_profile
  0.00     1.05      0.00        2     0.00     0.00  Module#method_added
  0.00     1.05      0.00      100     0.00     0.00  Fixnum#to_s
  0.00     1.05      0.00        1     0.00     0.00  Enumerable.to_a
  0.00     1.05      0.00        1     0.00  1015.00  #toplevel
  0.00     1.05      0.00        1     0.00     0.00  Array#join
  0.00     1.05      0.00        1     0.00     0.00  Range#each

Which shows that the regexp version is faster.  I assume, the string is
converted into a regexp internally and that this is done on each
invocation, while there are definitely optimizations for recurring regexp
usage.

Regards

    robert