Javari's Reference Immutability

Hasan Aljudy hasan.aljudy at gmail.com
Thu Jul 27 20:03:06 PDT 2006



Regan Heath wrote:
> On Thu, 27 Jul 2006 20:27:06 -0600, Hasan Aljudy 
> <hasan.aljudy at gmail.com>  wrote:
> 
>> Regan Heath wrote:
>>
>>> On Thu, 27 Jul 2006 18:39:29 -0600, Hasan Aljudy  
>>> <hasan.aljudy at gmail.com>  wrote:
>>>
>>>> You say that Java's String class implies alot of copying, therefor  
>>>> it's  bad. However, you fail to realize that copying when modifying 
>>>> is  exactly  what COW stands for. COW is a kind of honor-system 
>>>> protocol  implemented  by phobos. Everytime phobos thinks it needs 
>>>> to modify a  string which it  doesn't own, it makes a copy first to 
>>>> keep the  original string intact.  In Java, this can be done by 
>>>> creating a  StringBuffer from the String  (which creates a copy), 
>>>> after that, any  modification you make to  StringBuffer happens 
>>>> in-place; no needless  copying.
>>>
>>>   Sure. But are you trying to tell me that this..
>>>  String foo(String a) { .. return modified a .. }
>>> String bar(String a) { .. return modified a .. }
>>> String baz(String a) { .. return modified a .. }
>>> String bob(String a) { .. return modified a .. }
>>>  String s = foo(bar(baz(bob("test"))));
>>>  Will result in _no_ needless copying?
>>>  Regan
>>
>>
>> Same thing will happen will happen with phobos COW
> 
> 
> At present. This is the 'problem' I'd like to solve somehow.
> 
>> P.S. Are you (or Reiner Pope) saying that Javari provides a better  
>> solution to this? <g>
> 
> 
> No. I was just pointing out that Java's solution doesn't work for all  
> cases.
> 
> The reason it doesn't work is that String and StringBuffer are seperate  
> types. I think we need a single type (or 2 types which can be passed as 
> an  argument of the same name, perhaps 2 types where one is implicitly  
> convertable to the other). Either way, we need to know whether we need 
> to  .dup or not.
> 
> Regan

Well, for D, this can be solved with a non-COW versions of foo,baz, etc.

For Java, there is a possible solution that revolves around the same idea:

If a function is supposed to change the input string, and it's obvious 
(for example, if it's called toLower, toUpper .. etc), then it should 
take a StringBuffer, modify it in-place, and return it (as a StringBuffer).

If a String is passed, it can be implicitly converted to a StringBuffer 
(duplicated). (Ok, maybe this is not the current Java behaviour, but 
it's my porposed solution)
If a StringBuffer is passed, then it's all good.

This eliminates duplications in the given case. However, it creates a 
problem if the user expects a String return type:

StringBuffer foo(StringBuffer arg) { ... }

..
String a = "hi";
String b = foo(a);

this creates 2 duplicates: first duplicate a, then duplicate the 
returned string from foo.
(converting a StringBuffer to a String should create a duplicate, no?)





More information about the Digitalmars-d-learn mailing list