From: Kirk Haines Date: 2009-12-06T11:10:32+09:00 Subject: Re: Why doesn't Ruby "compile" strings? --0003255572a62e43d9047a05d8ef Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Sat, Dec 5, 2009 at 6:48 PM, I=F1aki Baz Castillo wrote: > Hi, the following code: > > ------------------- > #!/usr/bin/ruby > > require "benchmark" > > HELLO_WORLD =3D "hello world" > > 1.upto(4) do > > print "Benchmark using HELLO_WORLD: " > puts Benchmark.realtime { 1.upto(500000) {|i| HELLO_WORLD.upcase }= } > > print "Benchmark using \"hello_world\": " > puts Benchmark.realtime { 1.upto(500000) {|i| "hello_world".upcase= } > } > > print "Benchmark using 'hello_world': " > puts Benchmark.realtime { 1.upto(500000) {|i| 'hello_world'.upcase= } > } > > end > ------------------- > > > This clearly shows that using a constant string is faster than using a > string > writen into the script. So I wonder: why doesn't Ruby "precompile" > internally > the strings appearing in the script? > > This is because when you are using the constant, you are referring to the same object every time. When you are using the string literals, the interpreter doesn't know what you are going to do with that string literal, so it's not really safe for i= t to assume that it can use a single ruby object to represent all instances o= f it. Consequently, it creates a new object each time. So 500000.times { 'foo' } creates 500000 objects. That's obviously going t= o take more time than FOO =3D 'foo'; 500000.times { FOO } as that code just looks up a constant 500000 times. Kirk Haines --0003255572a62e43d9047a05d8ef--