Search code examples
javastringtimestringbuilder

Performance comparison of charAt() method of String vs StringBuilder in Java


I understand that StringBuilder is faster than String when it comes to operations that require some sort of mutation. However, if I only wish to access specific characters and no other operations are required, then is there any performance difference between the charAt() methods of both?

As a trivial example, if I needed to print the alternate characters of a string, starting from the first character, is there any preferred way to do it, of the two given below?

// 1
String dummyStr = "fhweyxnqwiynfgHINYUIYIOhuiw12341dfs";
for (int i = 0; i < dummyStr.length(); i += 2) {
    System.out.print(dummyStr.charAt(i));
}

// 2
StringBuilder dummySb = new StringBuilder(dummyStr);
for (int i = 0; i < dummySb.length(); i += 2) {
    System.out.print(dummySb.charAt(i));
}

Additionally, are there any benefits/drawbacks of doing it this way (using a char[]) instead?

// 3
char[] dummyArr = dummyStr.toCharArray();
for (int i = 0; i < dummyArr.length; i += 2) {
    System.out.print(dummyArr[i]);
}

Please note:
For this question, I am only concerned with the performance in terms of time, and not bothered about additional memory used. Also, the System.out.print() is merely a placeholder operation for the purpose of this example.


Solution

  • Both String and StringBuilder are backed by arrays and charAt() gets the value at the specified index.

    Since String is immutable, it must make a defensive copy before returning the array. So it has some additional overhead. But imo, this would only be a problem for very large strings or repeated conversion of many strings to arrays. It all depends how how you are using it.