首页 > 移动平台 > 详细

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

时间:2016-02-24 13:54:10      阅读:210      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!