区别不是很大;
测试多次,charAt效率略高
测试代码如下- public class Test1 {
- public static void main(String[] args) {
- new Test1().test();
- }
- public static void toArray(String str){
- char[] c=str.toCharArray();
- for(int i=0;i<c.length;i++){
- if(c[i]=='z'){
- System.out.println("ok");
- }
- System.out.print(c[i]);
- }
- }
- public static void charAt(String str){
- for(int i=0;i<str.length();i++){
- if(str.charAt(i)=='z'){
- System.out.println("ok");
- }
- System.out.print(str.charAt(i));
- }
- }
- @Test
- public void test(){
- long currentTime1=System.currentTimeMillis();
- for(int i=0;i<100000;i++){
- toArray("aaaaa");//和charAt不同的字符串,长度相同即可~
- }
- long costTime1=System.currentTimeMillis()-currentTime1;
-
- long currentTime2=System.currentTimeMillis();
- for(int i=0;i<100000;i++){
- charAt("bbbbb");
- }
- long costTime2=System.currentTimeMillis()-currentTime2;
- System.out.println();
- System.out.println(costTime1);
- System.out.println(costTime2);
- }
-
- }
复制代码
|