性能测试(做反射时,拼setter方法想到的)

来源:互联网 发布:淘宝返利群是真的吗 编辑:程序博客网 时间:2024/04/30 11:14
package test.reflection;public class ReflectionDemo3 {public static void main(String args[]){String str="name";createSetter(str);createSetter0(str);createSetter2(str);createSetter3(str);createSetter4(str);/** * 运行结果createSetter:1522  NamecreateSetter0:1864  NamecreateSetter2:3711  NamecreateSetter3:1073  NamecreateSetter3:884  Name */}public static void createSetter(String str){long t1=System.currentTimeMillis();StringBuffer buf=null;for(int i=0;i<9999999;i++){buf=new StringBuffer(str);char c=buf.charAt(0);String s=String.valueOf(c).toUpperCase();buf=buf.replace(0, 1,s );}long t2=System.currentTimeMillis();System.out.println("createSetter:\t"+(t2-t1)+" \t "+buf);}public static void createSetter0(String str){long t1=System.currentTimeMillis();StringBuffer buf=null;for(int i=0;i<9999999;i++){buf=new StringBuffer(str);char c=buf.charAt(0);String s=String.valueOf(c).toUpperCase();buf.delete(0,1).insert(0, s);}long t2=System.currentTimeMillis();System.out.println("createSetter0:\t"+(t2-t1)+" \t "+buf);}public static void createSetter2(String str){long t1=System.currentTimeMillis();for(int i=0;i<9999999;i++){char c=str.charAt(0);String s=String.valueOf(c);String su=s.toUpperCase();str=str.replaceFirst(s, su);}long t2=System.currentTimeMillis();System.out.println("createSetter2:\t"+(t2-t1)+" \t "+str);}public static void createSetter3(String str){long t1=System.currentTimeMillis();String newStr=null;for(int i=0;i<9999999;i++){newStr=str.substring(0, 1).toUpperCase()+str.substring(1);}long t2=System.currentTimeMillis();System.out.println("createSetter3:\t"+(t2-t1)+" \t "+newStr);}public static void createSetter4(String str){long t1=System.currentTimeMillis();StringBuffer buf=null;for(int i=0;i<9999999;i++){buf=new StringBuffer();buf.append(str.substring(0, 1).toUpperCase());buf.append(str.substring(1));}long t2=System.currentTimeMillis();System.out.println("createSetter3:\t"+(t2-t1)+" \t "+buf);}}

1 0
原创粉丝点击