Skip to content

Commit eec0c32

Browse files
committed
StringBuilder和StringBuffer有哪些区别呢
1 parent 5409ac0 commit eec0c32

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ stackoverflow-Java-top-qa
3030
> 性能
3131
3232
* [LinkedList、ArrayList各自的使用场景,如何确认应该用哪一个呢?](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/when-to-use-linkedlist-over-arraylist.md)
33+
* [StringBuilder和StringBuffer有哪些区别呢](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/stringbuilder-and-stringbuffer.md)
3334

3435

3536
### 待翻译问题链接(还剩x问题)
@@ -70,7 +71,6 @@ stackoverflow-Java-top-qa
7071
- [Comparing Java enum members: == or equals()?](http://stackoverflow.com/questions/1750435/comparing-java-enum-members-or-equals)
7172
- [Failed to load the JNI shared Library (JDK)](http://stackoverflow.com/questions/7352493/failed-to-load-the-jni-shared-library-jdk)
7273
- [Does Java support default parameter values?](http://stackoverflow.com/questions/997482/does-java-support-default-parameter-values)
73-
- [StringBuilder and StringBuffer](http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer)
7474
- [How to concatenate two arrays in Java?](http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java)
7575
- [What's the simplest way to print a Java array?](http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array)
7676
- [Why can't I switch on a String?](http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string)
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
##StringBuilder和StringBuffer有哪些区别呢
2+
3+
###最主要的区别,StringBuffer的实现使用了synchronized(锁),而StringBuilder没有。
4+
5+
因此,StringBuilder会比StringBuffer快。
6+
7+
如果你
8+
- 非常非常追求性能(其实这两个都不慢,比直接操作String,要快非常多了)
9+
- 不需要考虑线程安全问题,
10+
- JRE是1.5+
11+
12+
可以用StringBuilder,
13+
反之,请用StringBuffer。
14+
15+
性能测试例子:
16+
如下这个例子,使用StringBuffer,耗时2241ms,而StringBuilder是753ms
17+
```java
18+
public class Main {
19+
public static void main(String[] args) {
20+
int N = 77777777;
21+
long t;
22+
23+
{
24+
StringBuffer sb = new StringBuffer();
25+
t = System.currentTimeMillis();
26+
for (int i = N; i --> 0 ;) {
27+
sb.append("");
28+
}
29+
System.out.println(System.currentTimeMillis() - t);
30+
}
31+
32+
{
33+
StringBuilder sb = new StringBuilder();
34+
t = System.currentTimeMillis();
35+
for (int i = N; i --> 0 ;) {
36+
sb.append("");
37+
}
38+
System.out.println(System.currentTimeMillis() - t);
39+
}
40+
}
41+
}
42+
```
43+
44+
45+
stackoverflow讨论原址
46+
http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer

0 commit comments

Comments
 (0)