From c2cb5d57251c9941c585f8e7846babc1f6707d99 Mon Sep 17 00:00:00 2001 From: nathan Date: Wed, 17 Sep 2014 17:40:00 +0200 Subject: [PATCH] Added fast string replace --- Dorkbox-Util/src/dorkbox/util/Sys.java | 38 ++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Dorkbox-Util/src/dorkbox/util/Sys.java b/Dorkbox-Util/src/dorkbox/util/Sys.java index 3b49f0e..3f03a18 100644 --- a/Dorkbox-Util/src/dorkbox/util/Sys.java +++ b/Dorkbox-Util/src/dorkbox/util/Sys.java @@ -22,6 +22,8 @@ import java.util.Arrays; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; @@ -85,6 +87,42 @@ public class Sys { } } + /** + * FROM: https://www.cqse.eu/en/blog/string-replace-performance/ + * + * Replaces all occurrences of keys of the given map in the given string + * with the associated value in that map. + * + * This method is semantically the same as calling + * {@link String#replace(CharSequence, CharSequence)} for each of the + * entries in the map, but may be significantly faster for many replacements + * performed on a short string, since + * {@link String#replace(CharSequence, CharSequence)} uses regular + * expressions internally and results in many String object allocations when + * applied iteratively. + * + * The order in which replacements are applied depends on the order of the + * map's entry set. + */ + public static String replaceStringFast(String string, Map replacements) { + StringBuilder sb = new StringBuilder(string); + for (Entry entry : replacements.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + int start = sb.indexOf(key, 0); + while (start > -1) { + int end = start + key.length(); + int nextSearchStart = start + value.length(); + sb.replace(start, end, value); + start = sb.indexOf(key, nextSearchStart); + } + } + + return sb.toString(); + } + + public static String getSizePretty(final long size) { if (size > TERABYTE) { return String.format("%2.2fTB", (float) size / TERABYTE);