Utils: Add caching string split()

This commit is contained in:
zzz
2015-11-07 17:08:27 +00:00
parent 0762715264
commit e4ebb9a77d

View File

@ -37,6 +37,8 @@ import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.zip.Deflater;
import net.i2p.I2PAppContext;
@ -1889,4 +1891,38 @@ public class DataHelper {
}
return rv;
}
/**
* Same as s.split(regex) but caches the compiled pattern for speed.
* This saves about 10 microseconds (Bulldozer) on subsequent invocations.
*
* @param s non-null
* @param regex non-null
* @throws java.util.regex.PatternSyntaxException unchecked
* @since 0.9.24
*/
public static String[] split(String s, String regex) {
return split(s, regex, 0);
}
private static final ConcurrentHashMap<String, Pattern> patterns = new ConcurrentHashMap<String, Pattern>();
/**
* Same as s.split(regex, limit) but caches the compiled pattern for speed.
* This saves about 10 microseconds (Bulldozer) on subsequent invocations.
*
* @param s non-null
* @param regex non-null
* @param limit result threshold
* @throws java.util.regex.PatternSyntaxException unchecked
* @since 0.9.24
*/
public static String[] split(String s, String regex, int limit) {
Pattern p = patterns.get(regex);
if (p == null) {
p = Pattern.compile(regex);
patterns.putIfAbsent(regex, p);
}
return p.split(s, limit);
}
}