I am not an expert in Java; I am hoping that someone on this list who are more proficient in Java can help me out.
I have the following codes on my current server.
<cfset var buffer = CreateObject("java", "java.lang.StringBuffer").init("") />
<cfset buffer.append(variables.myVar) />
I am trying to move these codes to another server. The problem is that this new server (shared hosting) does not allow invoking of a Java Object. So, I changed them to the followings.
<cfset var buffer = "" />
<cfset var buffer = buffer & variables.myVar />
My question is, are the new codes equivalent to the old ones? What are the advantages of using java.lang.StringBuffer?
Thanks in advance,
Monte
No, the “new” code is less efficient when used in a heavy loop.
You can emulate StringBuffer with an array.
However: If you are not concatenating hundreds or thousands of strings in a row, there is little benefit in using StringBuffer. You can go with
&in most cases.I have done some testing (on a ColdFusion 7 server w/ Java 1.4, more recent editions might score differently).
All times are milli-seconds The results are averaged over 10 repeats (except the one in square brackets as this took virtually forever).
The following is the measurement of iteratively concatenating a single letter N times.
iterations concat array cfsave string content buffer 100 0 0 0 2 1000 4 4 2 22 10000 168 29 33 219 100000 30,781 168 293 1,575The following is the result of iteratively concatenating a string of length 10 N times:
iterations concat array cfsave string content buffer 100 0 0 0 4 1000 25 0 2 24 10000 1,242 33 31 232 100000 [410,979] 180 373 2,082Note how basic string concatenation gets rapidly more inefficient the more iterations you do and the longer the string gets. The other methods show more linar behavior.
Further notice that the StringBuffer’s performance is also tied to its initial size. If you dimension it too small (i.e. by calling
init("")instead of.init(10000), for example) then it is forced to re-allocate more space when it runs out, which also takes time. For the sake of test, I initialized it with exactly the amount of space it would need.