今天工作时遇到一个问题,就是在匹配某个字符串的最后是不是有SAAS,然后发现下面几个的性能相差极大。
比较contains,endWith,matchs,substring的性能
packagecom.zhou.utils.test;
publicclassContentTest {
publicstaticvoidmain(String[]args) {
Stringa="dasfnjkdsbnfjdksbgjbdfgjhbdfjfdhjSAAS";
getc(a);
gete(a);
getm(a);
gets(a);
}
publicstaticvoidgetc(Stringa){
longstart=System.nanoTime();
System.out.println(start);
if(a.contains("SAAS")){
System.out.println("SAAS");
}
longend=System.nanoTime();
System.out.println(end);
System.out.println("=============contains:"+(end-start));
}
publicstaticvoidgete(Stringa){
longstart=System.nanoTime();
System.out.println(start);
if(a.endsWith("SAAS")){
System.out.println("SAAS");
}
longend=System.nanoTime();
System.out.println(end);
System.out.println("=============endsWith:"+(end-start));
}
publicstaticvoidgetm(Stringa){
longstart=System.nanoTime();
System.out.println(start);
if(a.matches("SAAS")){
System.out.println("SAAS");
}
longend=System.nanoTime();
System.out.println(end);
System.out.println("=============matches:"+(end-start));
}
publicstaticvoidgets(Stringa){
longstart=System.nanoTime();
System.out.println(start);
if(a.substring(a.length()-4,a.length()).equals("SAAS")){
System.out.println("SAAS");
}
longend=System.nanoTime();
System.out.println(end);
System.out.println("=============substring:"+(end-start));
}
}
打印控制台的输出:
第一次
25395304228151
SAAS
25395304671292
=============contains:443141
25395305007672
SAAS
25395305092995
=============endsWith:85323
25395305175370
25395307892667
=============matches:2717297
25395308257130
SAAS
25395308401132
=============substring:144002
第二次
25756697567057
SAAS
25756697873127
=============contains:306070
25756698037838
SAAS
25756698114603
=============endsWith:76765
25756698198406
25756699453608
=============matches:1255202
25756699592423
SAAS
25756699682295
=============substring:89872
由上面可以看出,endWith的性能比其他几个,高出好几倍