Btw the java code works on char array that is copied into a string
(class?) i guess thats why it needs about 2x ram, what about
implementing it more like the c++ version
You mean String s;
forloop { s += 'char'; }
It will be way slower because String in java are immutable and with
each loop, a new string object will be created.
The quote below is from
http://www.acooke.org/andrew/immutable.html
the contents of the String class cannot be changed. any method that
you might expect to modify the contents actually returns a new
instance.
if you don't like this behaviour you might think of sub-classing
String to provide methods that do alter the contents. but this isn't
possible because the class is "final".
to see why, i think you have to look at how java passes arguments.
machine-level values - ints, floats and the like - are passed by
value. if you call foo.bar(i) then modifying the passed integer within
the bar method won't alter the value of i (of course!).
however, if we pass an object into a method, where the object's
contents are changed, then the effect will be seen outside the call.
this is passing by reference:
class Foo {
void changeStack( Stack inside ) {
inside.pop( ) ;
}
}
Stack s ;
s.push( new Object( ) ) ;
System.out.println( s.size( ) ) ; // here s has size 1
Foo f = new Foo( ) ;
f.changeStack( s ) ;
System.out.println( s.size( ) ) ; // here s has size 0
again, this is obvious, but note that it is different to the way in
which the machine-level values behave.
so how does this apply to String? unlike ints, literal strings
(sequences of characters in quotes) are not machine-level values -
they are String objects. so, in theory, passing "a quoted string" to a
method might result in the string changing value!
class FooFoo {
void changeString( String inside ) {
inside.append( " world" ) ; // pretend this changes the
String...
}
}
String s = "hello" ;
Foo f = new Foo( ) ;
f.changeString( s ) ;
System.out.println( s ) ; // ...then this would be "hello
world"...
f.changeString( "strange" ) ; // ...and what happens here?!
to avoid strange things like this last value (where a quoted string
would change value) the java designers would either have to have make
"quoted strings" machine-level values or introduce the idea of const
objects (similar to C++).
instead, the pragmatic solution is to make sure that the Sting class
can't change its contents - hence it is immutable and final.
and because String is immutable and final, it behaves as though it is
passed by value, not reference.