Posted

25 January 2008 @ 1pm

 

Java string reverse methods analyses

Following on from my previous post about making a simple palindrome detector, I analyse the performance of five different methods for reversing a string in Java.

First, here are 5 different reverse methods:

The good old for loop version


public static String reverse_loop (String in) {
    String out = "";
    for (int i=0; i<in.length(); i++) {
        out += String.valueOf(in.charAt((in.length()-1)-i));
    }
    return out;
}

A string buffer with an extra variable version


public static String reverse_buffer_var (String in) {
    StringBuffer sb = new StringBuffer(in).reverse();
    return sb.toString();
}

A string buffer without an extra variable version


public static String reverse_buffer (String in) {
    return new StringBuffer(in).reverse().toString();
}

A Recursive version from here


public static String reverse_recur (String in) {
    if (in.length() <= 1) {
        return in;
    }
    return reverse5(in.substring(1)) + in.charAt(0);
}

A tail recursive version from here


public static String reverse_tail_recur(String str) {
    if (str.length()  <= 1) {
        return str;
    }
    return reverse_tail_recur(str, "");
}

private static String reverse_tail_recur(String str, String acc) {
    if (str.length() == 0) {
        return acc;
    } else {
        return reverse_tail_recur(str.substring(1), str.charAt(0) + acc);
    }
}

So I created a string and passed it to each of these methods. Using NetBean’s performance tools I recorded the amount of time it took for each method to reverse the string and the results are as follows:

  1. reverse_buffer 0.077ms
  2. reverse_buffer_var 0.408ms
  3. reverse_recur 8.17ms
  4. reverse_tail_recur 10.76ms
  5. reverse_loop 73.2ms

So from this it is easy to see that the loop method is the slowest. It is also a good argument for using the JDK methods where available as using a StringBuffer and its reverse method was by far the quickest

Update

Found this post which reiterates that using a native method is probably the best course of action.

 

No Comments Yet

There are no comments yet. You could be the first!

Leave a Comment