Java String Iteration: The Hidden Performance Trap

This technical article compares two common approaches to string iteration in Java: traditional index-based iteration using charAt() versus enhanced for-loop with toCharArray(). Performance testing reveals that the character array method is significantly faster, taking only 91 microseconds compared to 200 microseconds for the charAt() approach. This finding suggests that using toCharArray() with enhanced for-loops is the more efficient choice for string iteration tasks in Java.

1 Minutes reading time

Behold the masterpiece that AI hallucinated while reading this post:

"The Tale of the Sluggish String Loop: A Java Performance Story"

(after I fed it way too many marketing blogs and memes)

Created using DALL-E 3

AI-Generated: The Tale of the Sluggish String Loop: A Java Performance Story

Often we need to iterate over a String. Java gives use several options. We can either use a simple loop with an index using the following style:

for (int i=0;i<theLine.length();i++) {
   char theCurrentChar = theLine.charAt(i);
   // Do something with the character
}

Or we can use the advanced for style using a character array the following way:

for (char theCurrentChar : theLine.toCharArray())  {
  // Do something with the character
}

Checking both options for performance gives us surprising results: Under heavy stress the first syntax takes in an advanced use case about 200 microseconds , the second syntax takes only 91 microseconds! It seems like the String.charAt() Method is the cause of our pain. The solution is also quite simple: always use the seconds syntax and you are safe!

Git revision: 2e692ad