Iterating over the characters in a string

I was wondering what would be the fastest method to iterate over the characters in a string with Java. A small test implements the following things:

  • using an Iterable
  • toCharArray()
  • charAt()
  • calling charAt() on a CharSequence

You can download the Eclipse project as a tar or zip or browse the code online here; have a look at the StringIteratorTest class first.

Results

Without further ado here are the results:

Variant Time in ms.
Iterator 5.5
toCharArray() 1.1
charAt() 1.6
CharSequence.charAt() 2.2

Bar chart of the test results

Conclusion

If speed is what you want you shouldn’t use Iterators but one of the other solutions instead. On the other hand if you just like to play with Iterators and classes that implement Iterable you may want to choose the slower solution.

Message from Test-King If want to learn JavaScript framework for your web project then download our 350-018 tutorials and 646-363 study guide for complete learning. Become expert with our 642-515 web development course.

1 comment so far ↓

Leave a Comment