Jean-Marc Orliaguet wrote:
cedric MARFIL wrote:
OK,
Thanks.
Python made the code easier and shorter using that syntax, but if java takes performances just to do the same,
I guess it would be better to use the + syntax:
String firstName = "Cedric";
String a = "Hello " + firstName;
In case of many elements to put in the string, it will render something like this: String a = "Hello " + firstName + ", how are you ? Did you have a good day on " + day + ". I guess it will be
better on " + date.toString() + ". See you".

Thanks

string concatenation using + is rather expensive, but it depends where you use it.

for large strings I usually do:

StringBuilder s = new StringBuilder();
s.append("...");
return s.toString()


Yes, in  fact you should *avoid* using string concatenation inside loops.
For example:

String str = "";
for (element : list) {
   str = str + ", "+ element;
}

This is wrong! It can be very expensive for large loops

Do it like this:
StringBuffer buf = new StringBuffer();
for (element : list) {
   buf.append(", ").append(element);
}
String str = buf.toString();

Why? Because each string concatenation (+) is transformed by the compiler in new StringBuffer().append() operations
In our case the code will be transformed by the compiler like this:
String str = "";
for (element : list) {
   str = new StringBuffer().append(str).append(element).toString();
}
or something similar
This means at each iteration the JVM is allocating at least one new object.
(allocation is expensive and extensive temporary allocations are generating important garbage for the GC)
By using a stringbuffer inside your loop you remove extra allocations.

Bogdan


and to do "real" formatting:

String.format("... %s, ... ", args)

which is closest to python's %

/JM
_______________________________________________
ECM mailing list
[email protected]
http://lists.nuxeo.com/mailman/listinfo/ecm


_______________________________________________
ECM mailing list
[email protected]
http://lists.nuxeo.com/mailman/listinfo/ecm

Reply via email to