我需要经常调用这个函数。基本上,它将所有重音字符替换为其非重音等价物,将空格更改为“_”,转换为小写,并去除其余的外来代码,因此可以安全地用作文件名/url路径/等。问题是,如您所见,从性能的角度来看,它看起来很糟糕。有人能想到更清洁、更快的替代方案吗?
public static String makeValidPathName(String rawString) {
if (rawString==null) return null;
rawString = rawString.replaceAll("[ÁÀÂÄáàäaàáâãäå]","a");
rawString = rawString.replaceAll("æ","ae");
rawString = rawString.replaceAll("çÇ","c");
rawString = rawString.replaceAll("[ÈÉÊËèéêë]","e");
rawString = rawString.replaceAll("[ìíîïÍÌÎÏ]","i");
rawString = rawString.replaceAll("ñÑ","n");
rawString = rawString.replaceAll("[ÓÓÖÔòóôõö]","o");
rawString = rawString.replaceAll("œ","oe");
rawString = rawString.replaceAll("[ÙÚÛÜùúûü]", "u");
rawString = rawString.replaceAll("[ýÿ]","y");
rawString= rawString.replaceAll("[^a-z A-Z 0-9 \\_ \\+]","");
rawString = rawString.replaceAll(" ","_");
return rawString.toLowerCase();
}
- - 编辑
好的,伙计们......我对所有 4 个案例进行了性能测试:
- 案例1)这里发布的原始例程。
- 案例2)@WChargin 建议的改进
- 案例 3)@devconsole 建议的查找表以及我对 SparseArray 的优化
- 案例 4)@Erik Pragt 建议的 Normalizer 方法
而且......获胜者是...... TADAAAA ......
D/REPLACEMENT_TEST(18563): *** Running Tests (1000 iterations)
D/REPLACEMENT_TEST(18563): Original REGEX : 13533 ms
D/REPLACEMENT_TEST(18563): Compiled REGEX : 12563 ms
D/REPLACEMENT_TEST(18563): Character LUT : 1840 ms
D/REPLACEMENT_TEST(18563): Java NORMALIZER : 2416 ms
- 有趣的是,模式编译优化并没有太大帮助。
- 我发现我对 REGEXES 速度的假设也是完全错误的,而 devconsole 在他对 Normalizer 优于正则表达式的有根据的猜测中是正确的。
- 令人惊讶的是 REGEXES 的速度有多慢。一个数量级的差异真的让我感到惊讶。我会尽量避免在 Java 上使用它们。
- 查找表是短边距最快的选项。我会坚持使用这个解决方案,因为有了 Normalizer 之一,我仍然需要手动替换一些字符(空格变成“_”),然后转换为小写。
测试是在三星 Galaxy Tab v1 10.1 中完成的。
请在附件中找到测试用例的源代码。
public class Misc {
/* Test 2 (@WCChargin's Regex compilation) initialization */
static Map<Pattern, String> patterns = new HashMap<Pattern, String>();
static {
patterns.put(Pattern.compile("[ÁÀÂÄáàäaàáâãäå]") ,"a");
patterns.put(Pattern.compile("æ"),"ae");
patterns.put(Pattern.compile("çÇ"),"c");
patterns.put(Pattern.compile("[ÈÉÊËèéêë]"),"e");
patterns.put(Pattern.compile("[ìíîïÍÌÎÏ]"),"i");
patterns.put(Pattern.compile("ñÑ"),"n");
patterns.put(Pattern.compile("[ÓÓÖÔòóôõö]"),"o");
patterns.put(Pattern.compile("œ"),"oe");
patterns.put(Pattern.compile("[ÙÚÛÜùúûü]"), "u");
patterns.put(Pattern.compile("[ýÿ]"),"y");
patterns.put(Pattern.compile("[^a-z A-Z 0-9 \\_ \\+]"),"");
patterns.put(Pattern.compile(" "),"_");
}
/* Test 3 (@devconsole's Lookup table) initialization */
static SparseArray<String> homeBrewPatterns=new SparseArray<String>();
/** helper function to fill the map where many different chars map to the same replacement */
static void fillMap(String chars, String replacement) { for (int i=0,len=chars.length(); i<len; i++) homeBrewPatterns.put(chars.charAt(i), replacement); }
static {
// fill the sparsearray map with all possible substitutions: Any char code gets its equivalent, ie, ä->a. a->a. A->a
// this also does the toLowerCase automatically. If a char is not in the list, it is forbidden and we skip it.
fillMap("ÁÀÂÄáàäaàáâãäå","a");
fillMap("æ","ae");
fillMap("çÇ","c");
fillMap("ÈÉÊËèéêë","e");
fillMap("ìíîïÍÌÎÏ","i");
fillMap("ñÑ","n");
fillMap("ÓÓÖÔòóôõö","o");
fillMap("œ","oe");
fillMap("ÙÚÛÜùúûü","u");
fillMap("ýÿ","y");
fillMap(" ","_");
for (char c='a'; c<='z'; c++) fillMap(""+c,""+c); // fill standard ASCII lowercase -> same letter
for (char c='A'; c<='Z'; c++) fillMap(""+c,(""+c).toLowerCase()); // fill standard ASCII uppercase -> uppercase
for (char c='0'; c<='9'; c++) fillMap(""+c,""+c); // fill numbers
}
/** FUNCTION TO TEST #1: Original function, no pattern compilation */
public static String makeValidPathName(String rawString) {
if (rawString==null) return null;
rawString = rawString.replaceAll("[ÁÀÂÄáàäaàáâãäå]","a");
rawString = rawString.replaceAll("æ","ae");
rawString = rawString.replaceAll("çÇ","c");
rawString = rawString.replaceAll("[ÈÉÊËèéêë]","e");
rawString = rawString.replaceAll("[ìíîïÍÌÎÏ]","i");
rawString = rawString.replaceAll("ñÑ","n");
rawString = rawString.replaceAll("[ÓÓÖÔòóôõö]","o");
rawString = rawString.replaceAll("œ","oe");
rawString = rawString.replaceAll("[ÙÚÛÜùúûü]", "u");
rawString = rawString.replaceAll("[ýÿ]","y");
rawString = rawString.replaceAll("[^a-z A-Z 0-9 \\_ \\+]","");
rawString = rawString.replaceAll(" ","_");
return rawString.toLowerCase();
}
/** FUNCTION TO TEST #2: @WCChargin's suggestion: Compile patterns then iterate a map */
public static String makeValidPathName_compiled(String rawString) {
for (Map.Entry<Pattern, String> e : patterns.entrySet()) {
rawString=e.getKey().matcher(rawString).replaceAll(e.getValue());
}
return rawString.toLowerCase();
}
/** FUNCTION TO TEST #3: @devconsole's suggestion: Create a LUT with all equivalences then append to a stringbuilder */
public static String makeValidPathName_lut(String rawString) {
StringBuilder purified=new StringBuilder(rawString.length()); // to avoid resizing
String aux; // to avoid creating objects inside the for
for (int i=0, len=rawString.length(); i<len; i++) {
aux=homeBrewPatterns.get(rawString.charAt(i));
if (aux!=null) purified.append(aux);
}
return purified.toString();
}
/** FUNCTION TO TEST #4: @Erik Pragt's suggestion on the use of a Normalizer */
public static String makeValidPathName_normalizer(String rawString) {
return rawString == null ? null
: Normalizer.normalize(rawString, Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
/** Test Runner as a Runnable, just do a Handler.post() to run it */
public static Runnable msStringReplacementTest=new Runnable() {
public void run() {
String XTAG="REPLACEMENT_TEST";
Log.d(XTAG, "*** Running Tests");
int ITERATIONS=1000;
String[] holder=new String[4];
/* http://www.adhesiontext.com/ to generate dummy long text ... its late n im tired :) */
String tester="e arte nací valse ojales i demediada cesé entrañan domó reo ere fiaréis cinesiterapia fina pronto mensuraré la desatufases adulantes toree fusca ramiro hez apolíneo insalvable atas no enorme mí ojo trola chao fas eh borda no consignataria uno ges no arenque ahuyento y daca pío veló tenle baúl ve birria filo rho fui tañe mean taz raicita alimentarías ano defunciones u reabráis repase apreciaran cantorales ungidas naftalina ex guió abomba o escribimos consultarás des usó saudí mercó yod aborrecieses guiri lupia ña adosado jeringara fe cabalgadura tú descasar diseñe amar limarme escobero latamente e oreó lujuria niñez fabularios da inviernen vejé estañarán dictará sil mírales emoción zar claudiquéis ó e ti ñ veintén dañen ríase esmeraras acató noté as mancharlos avisen chocarnos divertidas y relata nuera usé fié élitro baba upa cu enhornan da toa hechizase genesíacos sol fija aplicó gafa pi enes fin asé deal rolar recurran cacen ha id pis pisó democristiano oes eras lañó ch pino fijad ñ quita hondazos ñ determinad vid corearan corrompimiento pamema meso fofas ocio eco amagados pian bañarla balan cuatrimestrales pijojo desmandara merecedor nu asimiladores denunciándote jada ñudos por descifraseis oré pelote ro botó tu sí mejorado compatibilizaciones enyerba oyeses atinado papa borbón pe dé ñora semis prosada luces leí aconteciesen doy colmará o ve te modismos virola garbillen apostabas abstenido ha bajá le osar cima ají adormecéis ñu mohecí orden abrogándote dan acanilladas uta emú ha emporcara manila arribeña hollejo ver puntead ijadeáis chalanesca pechugón silbo arabescos e i o arenar oxidas palear ce oca enmaderen niñez acude topó aguanieves i aconsejaseis lago él roía grafito ceñir jopo nitritos mofe botáis nato compresores ñu asilo amerizan allanándola cuela ó han ice puya alta lío son de sebo antieconómicas alá aceza latitud faca lavé colocándolos concebirlo miserea ñus gro mearé enchivarse";
long time0=System.currentTimeMillis();
for (int i=0; i<ITERATIONS; i++) holder[0]=makeValidPathName(tester); // store in an array to avoid possible JIT optimizations
long elapsed0=System.currentTimeMillis()-time0;
Log.d(XTAG, "Original REGEX : "+elapsed0+" ms");
long time1=System.currentTimeMillis();
for (int i=0; i<ITERATIONS; i++) holder[1]=makeValidPathName_compiled(tester); // store in an array to avoid possible JIT optimizations
long elapsed1=System.currentTimeMillis()-time1;
Log.d(XTAG, "Compiled REGEX : "+elapsed1+" ms");
long time2=System.currentTimeMillis();
for (int i=0; i<ITERATIONS; i++) holder[2]=makeValidPathName_lut(tester); // store in an array to avoid possible JIT optimizations
long elapsed2=System.currentTimeMillis()-time2;
Log.d(XTAG, "Character LUT : "+elapsed2+" ms");
long time3=System.currentTimeMillis();
for (int i=0; i<ITERATIONS; i++) holder[3]=makeValidPathName_normalizer(tester); // store in an array to avoid possible JIT optimizations
long elapsed3=System.currentTimeMillis()-time3;
Log.d(XTAG, "Java NORMALIZER : "+elapsed3+" ms");
Log.d(XTAG, "Output 0: "+holder[0]);
Log.d(XTAG, "Output 1: "+holder[1]);
Log.d(XTAG, "Output 2: "+holder[2]);
Log.d(XTAG, "Output 3: "+holder[3]);
}
};
伙计们,非常感谢您的建议 :) 我喜欢 stackoverflow :)