0

After playing around with a simple palindrome function, I was surprised to find the performance difference between two different approaches.

public static boolean checkPalindrome(String inputString) {
    String[] arr = inputString.split("");
    for (int i = 0; i < arr.length / 2; i++) {
        if(!arr[i].equals(arr[arr.length - (i + 1)]))
            return false;
    }
    return true;
}

In this function I am only iterating through half of the array.

And in the following I would imagine that the whole array is iterated and a new object is created through the builder pattern.

public static boolean checkPalindrome2(String inputString) {
    return inputString.equals(new StringBuilder(inputString).reverse().toString());
}

I was extremely surprised to find that the first function has an average execution time of 550146 nano seconds, measure using System.nanoTime(), and the second has an average execution time of 61665 nano seconds, which is almost a tenfold increase in performance.

Could anybody help explain what is happening here?

James Wagstaff
  • 150
  • 1
  • 7
  • 7
    Does this answer your question? [How do I write a correct micro-benchmark in Java?](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – Johannes Kuhn May 31 '20 at 20:16
  • Also read https://stackoverflow.com/questions/196830/what-is-the-easiest-best-most-correct-way-to-iterate-through-the-characters-of-a – Savior May 31 '20 at 20:17
  • You are most likely executing the code in the interpreter. Therefore you allocate quite a lot String objects. – Johannes Kuhn May 31 '20 at 20:18
  • 1
    In the first version you do a lot of string comparisons. In the second version there's only *one* comparison. – Some programmer dude May 31 '20 at 20:21
  • 7
    Omit the `split` and compare _characters_ using `inputString.charAt(i)`. That's a more useful comparison. The splitting is expensive. – Gene May 31 '20 at 20:30
  • Gene thanks a lot, this is what I was looking for, a bit more information as to why. Johannes Kuhn no it doesn't, I was looking more towards the why there was such a performance difference. But still a very interesting read. Thanks! – James Wagstaff Jun 01 '20 at 00:23

0 Answers0