Re: std::string class instance are immutable or not??
On 6 Feb., 17:54, "Alf P. Steinbach" <al...@start.no> wrote:
* SG:
Assembling a string that way is very costly which is why in C# and in
Java you typically have a StringBuilder class which is like a string
but mutable.
I'm sorry but that is incorrect.
In Java it is the case (just tested on Sun's JVM/Compiler 1.6.0_10) by
wich I mean
a = a + ".";
in a loop is horribly slow. You are supposed to use a
java.lang.StringBuilder for this.
I'm not familiar with C#/.NET and it looks like there might be
compiler/VM magic involved w.r.t. the string class. So, yes, I can
imagine that in the .NET world string's "+=" isn't as bad as Java's
version. Still, what's the purpose of StringBuilder in C# if it wasn't
for speeding up string assembly.
With any reasonable string implementation '+=' is the most efficient possible
way to do concatenation, and since it avoids at least one conversion call it's
then more efficient than using a string builder (buffer) object.
I don't know what you mean by "conversion call" in this concext
but ... Yes, I can imagine an implementation where string objects
share character buffers and only manage their own start/end pointers.
So, if there's some yet unused and big enough room left in that buffer
there's no need to allocate a new buffer for concatenation. But you
might need to do some locking/synchronization.
In Java there is also a String member function "concat" which could do
what I described above. Just for kicks and giggles I wrote a simple
test in Java:
1: String a = "";
for (int k=0; k<0x10000; ++k) {
a = a + ".";
}
2: String a = "";
for (int k=0; k<0x10000; ++k) {
a = a.concat(".");
}
3: StringBuilder sb = new StringBuilder();
for (int k=0; k<0x10000; ++k) {
sb.append(".");
}
String a = sb.toString();
Test | Runtime
-----+---------------
1 | 10.369 seconds
2 | 2.624 seconds
3 | 0.076 seconds
As far as I know java.lang.StringBuilder doesn't do any kind of
locking/synchronization which is probably one reason it is so fast.
Alf, care to provide some C# test results just for the heck of it?
Cheers!
SG