- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to optimize string concatenation in Java
Problem Description
How to optimize string concatenation?
Solution
Following example shows performance of concatenation by using "+" operator and StringBuffer.append() method.
public class StringConcatenate { public static void main(String[] args) { long startTime = System.currentTimeMillis(); for(int i = 0; i < 5000; i++) { String result = "This is" + "testing the" + "difference"+ "between" + "String"+ "and"+ "StringBuffer"; } long endTime = System.currentTimeMillis(); System.out.println("Time taken for string" + "concatenation using + operator : " + (endTime - startTime)+ " ms"); long startTime1 = System.currentTimeMillis(); for(int i = 0; i < 5000; i++) { StringBuffer result = new StringBuffer(); result.append("This is"); result.append("testing the"); result.append("difference"); result.append("between"); result.append("String"); result.append("and"); result.append("StringBuffer"); } long endTime1 = System.currentTimeMillis(); System.out.println("Time taken for String concatenation" + "using StringBuffer : " + (endTime1 - startTime1)+ " ms"); } }
Result
The above code sample will produce the following result. The result may vary.
Time taken for stringconcatenation using + operator : 0 ms Time taken for String concatenationusing StringBuffer : 22 ms
Problem Description
How to do string concatenation ?
Solution
Following example shows concatenation string. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.
public class HelloWorld { public static void main(String []args) { String s = "Hello"; s = s.concat("word"); System.out.print(s); } }
Result
The above code sample will produce the following result. The result may vary.
Helloword
java_strings.htm
Advertisements