From: "Iñaki Baz Castillo" Date: 2009-12-06T11:20:01+09:00 Subject: Re: Why doesn't Ruby "compile" strings? El Domingo, 6 de Diciembre de 2009, Kirk Haines escribió: > On Sat, Dec 5, 2009 at 6:48 PM, Iñaki Baz Castillo wrote: > > Hi, the following code: > > > > ------------------- > > #!/usr/bin/ruby > > > > require "benchmark" > > > > HELLO_WORLD = "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 > it to assume that it can use a single ruby object to represent all > instances of it. Why not? It's obviously a string writen in the script, with no variables into it and so... -- Iñaki Baz Castillo