Android正则表达式使用及性能隐患分析

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

使用正则的实现方式:

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

第一种方式耗时可能会出现百毫秒级别的情况,这种情况跟正则表达式的复杂情况有关,使用的时候留意一下,打log日志跟踪时间

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

posted @ 2016-02-24 12:20  popfisher  阅读(522)  评论(0编辑  收藏  举报