So I came across a few articles claiming that string concatenation using + or (concat function is slower then using a buffered approach (StringBuffer or StringBuilder). I came across this post on the topic & ran the tests on my machine.
Results I got were something like this:
On avg concat was taking 4 sec & append was taking 1 ms. ( Number of iterations- 20000).
So I kept wondering why is it so slow really ? Is it because there is excessive copying or mutliple times space allocation ! So I modified Paul's code to add some extra testing function which you can find here at pastebin. Running the results on my & my friends machine gives very very different results:
Concat Append Alloc Set Value
My machine 4000 2ms 800 80
Friends machine 8000 2ms 400 1200
Large differnce in concat times could possibly be explained due to speed of machines. But how one explains a fuzzy pattern ? We found later that he was on Java 1.6 & I was on java 1.5 . But then why would my setval function be so fast & his alloc be so slow ? What are the changes done behind the curtain ?
If anyone of you does the same test,(which is easy- copy the file & run it!) do log ur results & reply back to me...
Update: Also we thought about it later- I was on Linux & he was on windows. Is memory allocation dependent on OS too ?
>>Is memory allocation dependent on OS too ?
ReplyDeleteYes. linux uses 4kb page size while windows can have variable page sizes...
Though, reasoning might be more intricate.