Many of my friends are preparing for interviews and the most basic interview question in Java is the difference between String, StringBuilder and StringBuffer and their performance tradeoffs. Where to use which one.
1. String Class
Benefits
How do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer is answer of this question.
2. StringBuffer is old class but StringBuilder is newly added in Java 5 along with major improvements like Enum, Generics, varargs methods and Autoboxing in Java.
1. String Class
- is immutable and final in Java.
- every modification in String object will result into creating a new String object.
- String is the one class which creates lots of garbage because of many temporary "Strings" created in program. => It is a performance issue.
- Representing string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are actually same instance of String. Also, comparing object with equality operator is bad practice in Java and you should always use equals method to check equality.
- String is represented using UTF-16 format in Java.
- You can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.
Benefits
- Immutability offers lot of benefit to the String class e.g. its Hash code value can be cached which makes it a faster Hashmap key and one of the reason why String is a popular key in HashMap.
- String is "final", so it can be safely shared between multiple threads without any extra synchronization. => reason for being a key (thread-safe)
- String overrides equals and hashcode() method => reason for being a key. Two Strings are considered to be equal if they contain exactly same character in same order and in same case.
Problem
Performance Overhead + garbage values -> Whenever you do operations on Strings e.g.converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc a new String is created ( coz its a immutable and final class) and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder.
Questions that you might face during the process :How do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer is answer of this question.
2. StringBuffer is old class but StringBuilder is newly added in Java 5 along with major improvements like Enum, Generics, varargs methods and Autoboxing in Java.
- StringBuilder & StringBuffer can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters.
- At any point, the length and content of the sequence can be changed through method invocations.
- You can convert a StringBuffer into String by its toString() method
- Use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java.
- StringBuilder and StringBuffer have all API methods similar.
- (String & StringBuffer) and (StringBuilder & String) are completely different and there API is also completely different.
- StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
Problems
- StringBuffer -> all its public methods are synchronized which makes it thread-safe but same time SLOW
Tips and Tricks ->
- StringBuilder whenever possible it performs better in most of cases than StringBuffer class.
- String is immutable while StringBuffer and StringBuilder is mutable object. => use String as keys in Hashmap
Found an implementation for showing the performance over internet -> public class ScratchPad {
static String a;
public static void main( String[] args ) throws Exception {
long time = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for( int i = 0; i < 10000000; i++ ) {
sb.delete( 0, sb.length() );
sb.append( "someString" );
sb.append( "someString2" );
sb.append( "someStrin4g" );
sb.append( "someStr5ing" );
sb.append( "someSt7ring" );
a = sb.toString();
}
System.out.println( System.currentTimeMillis()-time );
time = System.currentTimeMillis();
for( int i = 0; i < 10000000; i++ ) {
StringBuilder sb2 = new StringBuilder();
sb2.append( "someString" );
sb2.append( "someString2" );
sb2.append( "someStrin4g" );
sb2.append( "someStr5ing" );
sb2.append( "someSt7ring" );
a = sb2.toString();
}
System.out.println( System.currentTimeMillis()-time );
}
}
Results:
5016
7516
No comments:
Post a Comment