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 Name createSetter0: 1864 Name createSetter2: 3711 Name createSetter3: 1073 Name createSetter3: 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); } }
时间: 2024-09-27 19:09:59