From: "Iñaki Baz Castillo" Date: 2009-12-06T10:48:31+09:00 Subject: Why doesn't Ruby "compile" strings? 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 ------------------- gives these results: -------------------- Benchmark using HELLO_WORLD: 1.1907217502594 Benchmark using "hello_world": 1.53604388237 Benchmark using 'hello_world': 0.816991806030273 Benchmark using HELLO_WORLD: 0.599252462387085 Benchmark using "hello_world": 0.814466714859009 Benchmark using 'hello_world': 0.812573194503784 Benchmark using HELLO_WORLD: 0.595503330230713 Benchmark using "hello_world": 0.813859701156616 Benchmark using 'hello_world': 0.813681602478027 Benchmark using HELLO_WORLD: 0.594272136688232 Benchmark using "hello_world": 0.815742254257202 Benchmark using 'hello_world': 0.811828136444092 -------------------- Let's take the last result so Ruby is "entirely loaded": -------------------- Benchmark using HELLO_WORLD: 0.594272136688232 Benchmark using "hello_world": 0.815742254257202 Benchmark using 'hello_world': 0.811828136444092 -------------------- 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, when Ruby interpreter is parsing the script and founds "hello_world", couldn't it create the string *just once* and keep in memory forever so next time same string is accessed Ruby doesn't need to initiate it? Is it imposible due to the design of Ruby? PS: I don't know if other languages (Python, PHP, Perlo...) do it or not. -- Iñaki Baz Castillo