Alex Rivera | Logout

Java split String performances

Asked 2012-06-12T17:02:01.943
54

Here is the current code in my application:

String[] ids = str.split("/");

When profiling the application, a non-negligeable time is spent string splitting. Also, the split method takes a regular expression, which is superfluous here.

What alternative can I use in order to optimize the string splitting? Is StringUtils.split faster?

(I would've tried and tested myself but profiling my application takes a lot of time.)

Edit
Report

1 Answer

9

StringTokenizer is much faster for simple parsing like this (I did some benchmarking with a while back and you get huge speedups).

StringTokenizer st = new StringTokenizer("1/2/3","/");
String[] arr = new String[st.countTokens()];
arr[0] = st.nextToken();

If you want to eek out a little more performance, you can do it manually as well:

String s = "1/2/3"
char[] c = s.toCharArray();
LinkedList<String> ll = new LinkedList<String>();
int index = 0;

for(int i=0;i<c.length;i++) {
    if(c[i] == '/') {
        ll.add(s.substring(index,i));
        index = i+1;
    }
}

String[] arr = ll.size();
Iterator<String> iter = ll.iterator();
index = 0;

for(index = 0; iter.hasNext(); index++)
    arr[index++] = iter.next();
answered 2012-06-12T17:04:48.947

Your Answer