気になったことがあったので僕も実験してみた。
気になったのは、次の2つ。
- 正規表現のコンパイルを一回にしたらどれくらい改善できるのか
- 末尾から空白を検索した方が早くね?
結果は、
- trim2と同じか少し遅いくらいまで改善
- trim3と同じか少し早いくらい
- trim1はダントツで遅い
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Pattern; | |
public class Main { | |
private static final String VALUE = "あいう "; | |
public static void main(String[] args) { | |
long[] times = new long[6]; | |
times[0] = System.nanoTime(); | |
for(int i = 0; i < 10000; i++) { | |
trim1(VALUE); | |
} | |
times[1] = System.nanoTime(); | |
for(int i = 0; i < 10000; i++) { | |
trim2(VALUE); | |
} | |
times[2] = System.nanoTime(); | |
for(int i = 0; i < 10000; i++) { | |
trim3(VALUE); | |
} | |
times[3] = System.nanoTime(); | |
for(int i = 0; i < 10000; i++) { | |
trim4(VALUE); | |
} | |
times[4] = System.nanoTime(); | |
for(int i = 0; i < 10000; i++) { | |
trim5(VALUE); | |
} | |
times[5] = System.nanoTime(); | |
String fmt = "trim%d: %d"; | |
for(int i = 0; i < 5; i++){ | |
String str = String.format(fmt, i + 1, times[i + 1] - times[i]); | |
System.out.println(str); | |
} | |
} | |
public static String trim1(String value) { | |
return value.replaceAll("( | )+\\z", ""); | |
} | |
public static String trim2(String value) { | |
StringBuilder sb = new StringBuilder(value); | |
for(int i = sb.length()-1; 0 <= i; i--) { | |
char c = sb.charAt(i); | |
if(c == ' ' || c == ' ') sb.deleteCharAt(i); | |
else break; | |
} | |
return sb.toString(); | |
} | |
public static String trim3(String value) { | |
char[] ary = value.toCharArray(); | |
char[] trimed = new char[ary.length]; | |
for(int i = ary.length-1; 0 <= i; i--) { | |
if(ary[i] == ' ' || ary[i] == ' ') continue; | |
else trimed[i] = ary[i]; | |
} | |
return new String(trimed); | |
} | |
private static Pattern pattern = Pattern.compile("( | )+\\z"); | |
public static String trim4(String value) { | |
return pattern.matcher(value).replaceAll(""); | |
} | |
public static String trim5(String value) { | |
for(int index = value.length() - 1; 0 <= index; index--){ | |
char chr = value.charAt(index); | |
if(chr == ' ' || chr == ' '){ | |
continue; | |
} | |
return value.substring(0, index + 1); | |
} | |
return value; | |
} | |
} |
0 件のコメント:
コメントを投稿