From: "Mauricio Fernández" Date: 2002-10-23T23:55:14+09:00 Subject: Re: Things That Newcomers to Ruby Should Know (10/16/02) On Wed, Oct 23, 2002 at 09:35:34PM +0900, Gavin Sinclair wrote: > > Would it be possible for Ruby to know whether an object is referenced by > > several variables so += does '<<' or '... = ... + ...' when appropriate? > > > > Perhaps a bit in each String indicating whether it is shared or > > not would make it... and GC issues could be ignored at first. > > I don't think so. += is syntax sugar for you-know-what. Imagine trying to > explain to a newbie "... but except in this case ..." > > Side-effects are a part of life in Ruby (and not only in Ruby). Programmers > have to deal with them. They're not even a bad thing. [Disclaimer: I'm not proposing a modification of the language, see [52838] Even though there's a subtle change in the semantics, no code should break, and this is only an optimization, and nothing else] a = "bla bla" a += " --- wtf?" p a => "bla bla --- wft?" In this stupid example, we sure don't care whether Ruby is creating a new object or not, and the programmer doesn't mind having Ruby do a << " --- wtf?" instead of a = a + " --- wtf?" Now we certainly don't want Ruby to use '<<' internally in b = a b += " the object pointed to by a should not change!" I consider the use of '<<' when possible to be nothing but a slight optimization which might (or not) prove to make Ruby faster. You can do a "incomplete RC" (in fact I think something like that was already used in Ruby, somewhere), for the common case where an object is referenced only once. If another variable references it, set a "shared bit" to 1, and that's it. so you don't have to do complete RC which would be expensive. So we'd have a = "a" b = "b" a += "a" => a == "aa", using '<<' b = a => b == "aa" b += "b" => b == "aab", used ' = ... + ..." # simple RC in action now a += "a" => a == "aaa", using " = ... + ..." # cause the 'shared bit' wasn't reset, as we're not doing real RC This is not a language modification (unless somebody really needs a new object to be created *always* when doing +=), only a (possible) speed optimization. PS: I'm getting a computer of my own next week, and as I'm gonna have a lot of free time, I may try this and other different tricks on Ruby's implementation, following my new policy on how to improve Ruby [52838] http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/52838 -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com Stupid nick highlighting Whenever someone starts with "stupid" it highlights the nick. Hmm. -- #Debian