è¿ä¸ªæ¯stringç±»
https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=ZH-CN&k=k(string_CSharpKeyword);k(string);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv3.5);k(DevLang-csharp)&rd=true
è¿ä¸ªæ¯stringBufferç±»
https://msdn.microsoft.com/zh-cn/library/system.text.stringbuilder(v=vs.110).aspx
å¨javaä¸æ3个类æ¥è´è´£å符çæä½ã
1.Character æ¯è¿è¡å个å符æä½çï¼
2.String 对ä¸ä¸²å符è¿è¡æä½ãä¸å¯åç±»ã
3.StringBuffer ä¹æ¯å¯¹ä¸ä¸²å符è¿è¡æä½ï¼ä½æ¯å¯åç±»ã
String:
æ¯å¯¹è±¡ä¸æ¯åå§ç±»å.
为ä¸å¯å对象,ä¸æ¦è¢«å建,å°±ä¸è½ä¿®æ¹å®çå¼.
对äºå·²ç»åå¨çString对象çä¿®æ¹é½æ¯éæ°å建ä¸ä¸ªæ°ç对象,ç¶åææ°çå¼ä¿åè¿å».
String æ¯finalç±»,å³ä¸è½è¢«ç»§æ¿.
StringBuffer:
æ¯ä¸ä¸ªå¯å对象,å½å¯¹ä»è¿è¡ä¿®æ¹çæ¶åä¸ä¼åStringé£æ ·éæ°å»ºç«å¯¹è±¡
å®åªè½éè¿æé å½æ°æ¥å»ºç«,
StringBuffer sb = new StringBuffer();
note:ä¸è½éè¿ä»å¼ç¬¦å·å¯¹ä»è¿è¡ä»å¼.
sb = "welcome to here!";//error
对象被建ç«ä»¥å,å¨å
åä¸å°±ä¼åé
å
å空é´,并åå§ä¿åä¸ä¸ªnull.åStringBuffer
ä¸ä»å¼çæ¶åå¯ä»¥éè¿å®çappendæ¹æ³.
sb.append("hello");
å符串è¿æ¥æä½ä¸StringBufferçæçè¦æ¯Stringé«:
String str = new String("welcome to ");
str += "here";
çå¤çæ¥éª¤å®é
ä¸æ¯éè¿å»ºç«ä¸ä¸ªStringBuffer,让侯è°ç¨append(),æå
åå°StringBuffer toSting();
è¿æ ·çè¯Stringçè¿æ¥æä½å°±æ¯StringBufferå¤åºäºä¸äºéå æä½,å½ç¶æçä¸è¦æææ£.
并ä¸ç±äºString 对象æ¯ä¸å¯å对象,æ¯æ¬¡æä½Sting é½ä¼éæ°å»ºç«æ°ç对象æ¥ä¿åæ°çå¼.
è¿æ ·åæ¥ç对象就没ç¨äº,å°±è¦è¢«åå¾åæ¶.è¿ä¹æ¯è¦å½±åæ§è½ç.
çç以ä¸ä»£ç ï¼
å°26个è±æåæ¯éå¤å äº5000次ï¼
String tempstr = "abcdefghijklmnopqrstuvwxyz";
int times = 5000;
long lstart1 = System.currentTimeMillis();
String str = "";
for (int i = 0; i < times; i++) {
str += tempstr;
}
long lend1 = System.currentTimeMillis();
long time = (lend1 - lstart1);
System.out.println(time);
å¯ææç计ç®æºä¸æ¯è¶
级计ç®æºï¼å¾å°çç»ææ¯æ¬¡ä¸ä¸å®ä¸æ ·ä¸è¬ä¸º 46687å·¦å³ã
ä¹å°±æ¯46ç§ã
æ们åçç以ä¸ä»£ç
String tempstr = "abcdefghijklmnopqrstuvwxyz";
int times = 5000;
long lstart2 = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < times; i++) {
sb.append(tempstr);
}
long lend2 = System.currentTimeMillis();
long time2 = (lend2 - lstart2);
System.out.println(time2);
å¾å°çç»æ为 16 ææ¶è¿æ¯ 0
æ以ç»è®ºå¾ææ¾ï¼StringBuffer çé度å ä¹æ¯String ä¸ä¸åãå½ç¶è¿ä¸ªæ°æ®ä¸æ¯å¾åç¡®ãå 为循ç¯ç次æ°å¨100000次çæ¶åï¼å·®å¼æ´å¤§ãä¸ä¿¡ä½ è¯è¯ã
æ ¹æ®ä¸é¢æ说ï¼
str += "here";
çå¤çæ¥éª¤å®é
ä¸æ¯éè¿å»ºç«ä¸ä¸ªStringBuffer,让侯è°ç¨append(),æå
åå°StringBuffer toSting();
æ以str += "here";å¯ä»¥çåäº
StringBuffer sb = new StringBuffer(str);
sb.append("here");
str = sb.toString();
æ以ä¸é¢ç´æ¥å©ç¨"+"æ¥è¿æ¥Stringç代ç å¯ä»¥åºæ¬çåäºä»¥ä¸ä»£ç
String tempstr = "abcdefghijklmnopqrstuvwxyz";
int times = 5000;
long lstart2 = System.currentTimeMillis();
String str = "";
for (int i = 0; i < times; i++) {
StringBuffer sb = new StringBuffer(str);
sb.append(tempstr);
str = sb.toString();
}
long lend2 = System.currentTimeMillis();
long time2 = (lend2 - lstart2);
System.out.println(time2);
å¹³åæ§è¡æ¶é´ä¸º46922å·¦å³ï¼ä¹å°±æ¯46ç§ã
æ»ç»: å¦æå¨ç¨åºä¸éè¦å¯¹å符串è¿è¡é¢ç¹çä¿®æ¹è¿æ¥æä½çè¯.使ç¨StringBufferæ§è½ä¼æ´é«