Home » Java » Java – Most Efficent way to traverse a String [duplicate]

Java – Most Efficent way to traverse a String [duplicate]

Posted by: admin December 28, 2021 Leave a comment


Possible Duplicate:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?

What I’m considering is time and efficiency. With those in mind, which method (among the ones below or others not mentioned) is the most efficient way to go through each character of a string?

String str = "Foo Bar";
for(int i=0;i<str.length();i++)
   System.out.println(str.charAt(i)); // access the character using .charAt()

for(char letter: str.toCharArray)
   System.out.println(letter);       // use for-each loop with the char array.

Again, there might be a better way to do this, but I also am curious if there is are major time/resources differences between the two above.


The first version is more efficient. The second version of the code will end up being slower and use more memory because of the cost of creating and filling the new char[] with toCharArray().

For long strings (more than 512 chars, approximately), the fastest way to inspect the string is to use reflection to access the backing char[] of the String (but only works up to Java 8, because of Compact Strings):

String data = "a really long string";
Field field = String.class.getDeclaredField("value");
char[] chars = (char[]) field.get(data);

for (int i = 0, n = chars.length; i < n; i++)

By using the above approach, we were able to avoid entirely the need to create a new char[] and also to pay the cost of an extra method call to charAt() in each iteration.

Take a look at this post, the answer contains detailed benchmarks. The best of both worlds, but anyway it was a hack and it no longer works.


The first method is faster since toCharArray has to copy over the internal character array of the string before it returns anything, whereas charAt accesses the elements from this internal array directly, making it more efficient.

In other words, charAt is O(1) and toCharArray is O(n). Now, both of those methods of traversing the string will be O(n), but the second will have a higher ‘leading coefficient’ than the first.

You can see all this if you look at the source code for the String class.