Java.toCharArray()和charAt()的效率對(duì)比分析
LeetCode中的一道算法題,使用toCharArray()時(shí)間超時(shí),換成charAt()之后通過(guò),所以測(cè)試一下兩者的運(yùn)行效率:
public static void test() { String s = 'a'; for(int i = 0; i < 100000; i++) { s += 'a'; } long start1 = System.currentTimeMillis(); char[] cs = s.toCharArray(); for(char c:cs) { System.out.println(1); // 需要輸入語(yǔ)句進(jìn)入循環(huán) } long end1 = System.currentTimeMillis(); long start2 = System.currentTimeMillis(); for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); System.out.println(1); } long end2 = System.currentTimeMillis(); System.out.println(end1 - start1); System.out.println(end2 - start2); }
結(jié)果證明charAr()效率較高些,運(yùn)行結(jié)果為:
1980
1443
補(bǔ)充知識(shí):JAVA: toCharArray()類 將字符串轉(zhuǎn)為數(shù)組
我就廢話不多說(shuō)了,大家還是直接看代碼吧~
public class Demo {public static void main(String[] args){String str = 'helloworld'; char[] data = str.toCharArray();// 將字符串轉(zhuǎn)為數(shù)組 for (int x = 0; x < data.length; x++) { System.out.print(data[x] + ' '); data[x] -= 32; System.out.print(data[x] + ' '); } System.out.println(new String(data));}}
以上這篇Java.toCharArray()和charAt()的效率對(duì)比分析就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python 如何在 Matplotlib 中繪制垂直線2. ASP常用日期格式化函數(shù) FormatDate()3. 開發(fā)效率翻倍的Web API使用技巧4. 如何通過(guò)python實(shí)現(xiàn)IOU計(jì)算代碼實(shí)例5. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. Python 操作 MySQL數(shù)據(jù)庫(kù)9. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式10. python中@contextmanager實(shí)例用法
