您的位置:首页 > 移动开发 > Android开发

在Android里面使用正则有性能隐患

2016-02-24 12:20 501 查看
场景:找出一个关键词在一条短信中出现的次数

使用正则的实现方式:

public static int findKeyWordCount(String srcText, String keyword) {
int count = 0;
Pattern p = Pattern.compile(keyword);
Matcher m = p.matcher(srcText);
while (m.find()) {
count++;
}
return count;
}


普通方式:

public static int getSubCount(String str, String key) {
int count = 0;
int index = 0;
while ((index = str.indexOf(key, index)) != -1) {
index = index + key.length();
count++;
}
return count;
}


第一种方式耗时是百毫秒级别的,第二种是几毫秒级别的,如果有性能方面的考虑,请小心使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: