“StringBuffer 是同步的(或线程安全的),而 StringBuilder 不是”,为什么这会使 StringBuffer 方法变慢?
读完这篇文章后 - 'synchronized' 是什么意思? 我仍然无法理解为什么 StringBuffer 会在线程安全环境中比 StringBuilder 慢。 StringBuffer 必须做哪些额外的耗时工作才使其变慢?
After reading this - What does 'synchronized' mean? I was still unable to understand why StringBuffer would be slower than StringBuilder in a thread-safe environment. What extra time-consuming work does StringBuffer have to do that makes it slower?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
即使获取和释放无竞争的锁,也会有一些小的开销,并且锁省略即使大多数实例不跨线程使用,它也不会在
StringBuffer
中工作,因为实例可以跨线程使用。请参阅http://book.javanb.com/java-threads-3rd /jthreads3-CHP-5-SECT-1.html 了解 VM 在获取和释放锁时必须执行的操作的描述。
There is some small overhead acquiring and releasing even an uncontended lock, and lock elision won't work in
StringBuffer
even if most instances are not used cross-thread because an instance could be.See http://book.javanb.com/java-threads-3rd/jthreads3-CHP-5-SECT-1.html for a description of what the VM has to do when acquiring and releasing locks.
确保一切同步运行。或者,更重要的是,不同步。同步方法调用意味着该方法的两次不同调用(如果该对象不是静态的,则在该对象上)必须轮流进入该方法。在线程 A(已在该方法中)完成之前,线程 B 无法进入方法synchMeth。
检查同步块是否已被锁定以及由谁锁定需要额外的时间。
Making sure things are running in synch. Or, more to the point, out of synch. Synchronizing a method call means two different invocations of that method (on that object if it is not static) have to take turns entering the method. Thread B cannot enter method synchMeth until Thread A (already in the method) has finished.
The checks for whether a synchronized block has been locked or not, and by whom, take extra time.
从 JavaDoc 阅读此内容
您必须阅读这篇文章 StringBuffer 与 StringBuilder 性能比较< /a>
其他有用的链接:StringBuffer 和 StringBuilder 类之间的区别。
Read this from JavaDoc
You must read this article on StringBuffer vs. StringBuilder performance comparison
Additional Useful Link : Difference between StringBuffer and StringBuilder class.