前回の記事でJavaで超簡単な文字列の数値チェックを紹介したのですが、正規表現を使用したパターンとどちらが速いのか気になったので検証してみました。
超簡単な文字列の数値チェックについてはこちら
パフォーマンスとかそういうのはひとまず考えず、超簡単にできる文字列の数値チェックをご紹介
コード
	/**
	 * 数値チェック
	...
コード
public class Main {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 数値(小数なし)
		String str1 = "10";
		// 数値(小数あり)
		String str2 = "10.01";
		// 数値以外
		String str3 = "10#01";
		for (int count = 0; count < 3; count++) {
			System.out.println(count + 1 + "回目");
			{
				long startTime = System.currentTimeMillis();
				for (int i = 0; i < 1000000; i++) {
					boolean b1 = isNumByMatche(str1);
					boolean b2 = isNumByMatche(str2);
					boolean b3 = isNumByMatche(str3);
				}
				long endTime = System.currentTimeMillis();
				long elapsedTime = endTime - startTime;
				System.out.println("正規表現でチェック: " + elapsedTime + "ミリ秒");
			}
			{
				long startTime = System.currentTimeMillis();
				for (int i = 0; i < 1000000; i++) {
					boolean b1 = isNumByParse(str1);
					boolean b2 = isNumByParse(str2);
					boolean b3 = isNumByParse(str3);
				}
				long endTime = System.currentTimeMillis();
				long elapsedTime = endTime - startTime;
				System.out.println("数値変換でチェック: " + elapsedTime + "ミリ秒");
			}
			System.out.println("");
		}
        }
	/**
	 * 数値チェック(数値変換を使用)
	 * @param str チェック対象
	 * @return
	 */
	public static boolean isNumByParse(String  str) {
		try {
			Double.parseDouble(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	private static final String NUM_PATTERN = "-?[0-9]+(\\.[0-9]+)?";
	/**
	 * 数値チェック(正規表現を使用)
	 * @param str チェック対象
	 * @return
	 */
	public static boolean isNumByMatche(String str) {
		if (str == null || str.length() == 0) {
			return false;
		}
		return str.matches(NUM_PATTERN);
	}
}
実行結果
1回目 正規表現でチェック: 2482ミリ秒 数値変換でチェック: 1023ミリ秒 2回目 正規表現でチェック: 2379ミリ秒 数値変換でチェック: 1035ミリ秒 3回目 正規表現でチェック: 2422ミリ秒 数値変換でチェック: 1019ミリ秒
まとめ
丁寧に正規表現でチェックするよりも数値変換という力業でチェックした方が速い!
やはり力こそ全て…力こそ正義…