Moved simple string split from benchmark to util class

This commit is contained in:
Ziver Koc 2016-07-14 17:49:06 +02:00
parent dc91d5e992
commit 95586441ee
2 changed files with 29 additions and 10 deletions

View file

@ -28,6 +28,7 @@ import zutil.converter.Converter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* This is a class whit utility methods.
@ -214,4 +215,29 @@ public class StringUtil {
}
return SPACES.get(i);
}
/**
* A simple split method that uses {@link String#substring(int, int)}
* to split a string between a single character delimiter.
* This method should be used for performance reasons as it is faster than
* the {@link String#split(String)}.
*
* @param str is the string to be split
* @param delimiter a single character delimiter
* @return a List with all data between the delimiter
*/
public static List<String> split(String str, char delimiter){
ArrayList<String> splitList = new ArrayList<>();
int from = 0, to = 0;
while (to >= 0) {
to = str.indexOf(delimiter, from + 1);
if (to < 0)
splitList.add(str.substring(from));
else
splitList.add(str.substring(from, to));
from = to;
}
return splitList;
}
}

View file

@ -4,8 +4,10 @@ import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;
import org.junit.Rule;
import org.junit.Test;
import zutil.StringUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
@ -39,16 +41,7 @@ public class StringSplitBenchmark {
@Test
public void substring(){
for(int i=0; i<TEST_EXECUTIONS; i++) {
ArrayList<String> splitList = new ArrayList<>();
int from = 0, to = 0;
while (to >= 0) {
to = str.indexOf(delimiter, from + 1);
if (to < 0)
splitList.add(str.substring(from));
else
splitList.add(str.substring(from, to));
from = to;
}
List<String> splitList = StringUtil.split(str, delimiter.charAt(0));
assertSplit(splitList.toArray(new String[splitList.size()]));
}
}