码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-02-24 13:56:06      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

场景:找出一个关键词在一条短信中出现的次数

使用正则的实现方式:

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;
}    

第一种方式耗时是百毫秒级别的,第二种是几毫秒级别的,如果有性能方面的考虑,请小心使用

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

标签:

原文地址:http://www.cnblogs.com/popfisher/p/5212518.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!