Can synchronization be optimised away?
Overview There is a common misconception that because the JIT is smart and synchronization can be eliminated for an object which is only local to a method that there is no performance impact. A test comparing StringBuffer and StringBuilder These two classes do basically the same thing except one is synchronized (StringBuffer) and the other is not. It is also a class which is often used in one method to build a String. The following test attempts to determine how much difference using one other the other can make. static String dontOptimiseAway = null; static String[] words = new String[100000]; public static void main(String... args) { for (int i = 0; i < words.length; i++) words[i] = Integer.toString(i); for (int i = 0; i < 10; i++) { dontOptimiseAway = testStringBuffer(); dontOptimiseAway = testStringBuilder(); } } private static String testStringBuffer() { long start = System.nanoTime(); StringBuffer sb = new StringBuffer();