Re: std::string class instance are immutable or not??
Hi Alf,
thanks for taking the time to do this test! I really was curious about
how the different variants in C# and in Java compare but I don't have
a C# compiler handy.
On 6 Feb., 22:26, "Alf P. Steinbach" wrote:
SG wrote:
a = a + ".";
I'm sorry but that is a misunderstanding and /very/ different from the ex=
ample I
commented on.
I'm aware of that. I seem to have forgotten about the existence of +=
on strings in Java. The method I believed to come closest is the
member function String.concat which I included in the test.
Have you really tested Java's version of '+=' or have you tested infix =
'+'?
I tested the three cases: 1. Infix +, 2. member function concat and 3.
StringBuilder.
3: StringBuilder sb = new StringBuilder();
for (int k=0; k<0x10000; ++k) {
sb.append(".");
}
String a = sb.toString();
#3 looks like C# not Java, and you're not testing '+='.
It is indeed fraction of valid Java (except for the "3:"). You were
able to compile it as far as I can tell. :)
C:\temp> java ConcatTest
Infix '+' : 12,33
concat : 02,84
builder : 00,02
'+=' operator: 11,83
This matches my measurements. I guess the JVM/compiler builders don't
see the need to optimize infix+ and += with having a StringBuilder
available.
<results language="C#">
C:\temp> concat
Infix '+' : 00,46
concat : 00,44
builder : 00,09
'+=' operator: 00,38
Interesting.
<results language="C++">
C:\temp> a
Infix '+' : 0.0940
concat : 0.0000
'+=' operator: 0.0000
a = a.concat("."); // is probably equivalent to
a = a += "."; // where the self-assignment check just returns
So, in summary, at least for C++ programming it is, as I noted earlier, a=
really
good idea to use '+=' (or equivalently 'append') instead of infix '+', =
and a
really bad idea to do the opposite. And it is surprising that the Java an=
d C#
compilers don't implement '+=' efficiently; it's easy to do. I thought =
they did.
Thanks again for the thorough testing.
Cheers!
SG