This is something related to the java performance: answer for a where, which and what code to use problem. Let me start with introducing the problem.
When we coding java we are normally use string concatenation and string replacements in our code. But when we encounter a java based solution which need string concatenation and string replacement we never think about the order which we should execute them in ordered to maximize the performance. So the problem here is do we need to concat first or replace string first to high performance? (Please note that this is not valid for all the cases where you need to concat and string replace)
So I thought about a method to measure the performance of in each case.
Case 1 - Concatenation then Replace
Here is the method I used to measure the performance. k is the number of concatenations.
public long testConcatReplace(int k){ long t = new Date().getTime(); for(int j=0;j<10000;j++) { String str = "I am the best"; StringBuffer s = new StringBuffer(str); for(int i=0;i<k;i++){ s = s.append(s); } s.toString().replaceAll(" ", ""); } return new Date().getTime() - t; }
Here is the average time value for executing this method for different k values.
k | time |
---|---|
1 | 11 |
2 | 25 |
3 | 42 |
4 | 60 |
5 | 148 |
6 | 231 |
7 | 565 |
8 | 1001 |
Case 2 - Replace then Concatenation
Here is the method I used to measure the performance. k is the number of concatenations.
Here is the method I used to measure the performance. k is the number of concatenations.
Here is the average time value for executing this method for different k values.
public long testReplaceConcat(int k){ long t = new Date().getTime(); for(int j=0;j<10000;j++) { String str = "I am the best"; StringBuffer s = new StringBuffer(str.replaceAll(" ", "")); for(int i=0;i<k;i++){ s = s.append(str.replaceAll(" ", "")); } } return new Date().getTime() - t; }
Here is the average time value for executing this method for different k values.
k | time |
---|---|
1 | 20 |
2 | 26 |
3 | 41 |
4 | 47 |
5 | 57 |
6 | 67 |
7 | 84 |
8 | 92 |
Here is the comparison of both results in a graph.
Observation:
String replacement is a expensive process and the time for the operation is exponentially increase with the length of the string.
Concatenation is somewhat expensive but the time consume for concatenation of any two string is almost equal.
Conclusion:
You can increase the the string replace performance of your java code by executing the string replacement before concatenation.
Environment:
OS - Mint Linux 12
CPU - Intel(R) Core(TM) i7-2630QM CPU @ 2.00GHz
RAM - 8 GB