From: "Iñaki Baz Castillo" Date: 2009-12-07T01:41:11+09:00 Subject: Re: Why doesn't Ruby "compile" strings? El Domingo, 6 de Diciembre de 2009, Robert Klemme escribió: > On 06.12.2009 11:17, Brian Candler wrote: > > Iñaki Baz Castillo wrote: > >>> 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... > > > > Suppose you do: > > > > 10.times do > > puts "hello" > > end > > > > The interpreter has no way of knowing that puts does not mutate the > > argument passed to it. This is a silly example, but you might have done: > > > > alias :old_puts :puts > > def puts(x) > > old_puts x > > x.replace "rubbish" > > end > > > > So it is forced to create a new string object each time round the loop. > > > > It's a shame that Ruby doesn't have immutable strings. Symbols are the > > closest, but they have different semantics to strings. > > > > If the literal syntax "xxx" gave a *frozen* String, then it would be > > safe to re-use it. But then if you wanted to append to a string, you'd > > have to write: > > > > a = "".dup > > a << "stuff" > > > > or perhaps > > > > a = String.new > > a << "stuff" > > Another thing you could not do with the auto interning (as with Java > String constants): > > ...each do |whatever| > s = "intro " << whatever << " outro" > store_away(s) > end > > Ruby leaves the decision up to you where you want to optimize while > still keeping things nice for other use cases. The code above would > have to look like this if "" and '' would not construct new objects: > > ...each do |whatever| > s = "intro ".dup << whatever << " outro" > store_away(s) > end > > Now, that looks worse IMHO. > > Kind regards > > robert > > > PS: Note also that all strings created via "" and '' do share the > internal character buffer until one of them is modified (copy on write) > so it could be more inefficient as it actually is. :-) Ok, thanks a lot to all for so good explanations. 100% understood now :) -- Iñaki Baz Castillo