

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we compare a StringBuilder with StringBuffer in Java?
The StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time. The StringBuilder is a replacement for the thread-safe StringBuffer class and it works much faster as it has no synchronized methods. If we are doing lots of String operations in a single thread, we can gain a lot of performance when using this class.
Example
public class CompareBuilderwithBufferTest { public static void main(String []args) { stringBufferTest(); stringBuilderTest(); } public static void stringBufferTest() { long startTime = System.nanoTime(); StringBuffer sb = new StringBuffer(); for (int i=0; i < 1000; i++) { sb.append((char) 'a'); } System.out.println("StringBuffer test: " + (System.nanoTime() - startTime)); } public static void stringBuilderTest() { long startTime = System.nanoTime(); StringBuilder sb = new StringBuilder(); for (int i=0; i < 1000; i++) { sb.append((char) 'a'); } System.out.println("StringBuilder test: " + (System.nanoTime() - startTime)); } }
Output
StringBuffer test: 192595 StringBuilder test: 85733
- Related Questions & Answers
- Java String, StringBuffer and StringBuilder Tutorial.
- Difference between StringBuilder and StringBuffer in Java
- Difference between StringBuffer and StringBuilder.
- Where to use a StringBuffer/StringBuilder than a String in Java?
- What is the difference between a StringBuffer and StringBuilder in java?
- What is the difference between StringBuffer and StringBuilder in java?
- How can we replace specific part of String and StringBuffer in Java?
- How can I clear or empty a StringBuilder in Java.
- Can we compare Akshay Kumar with Jackie Chan?
- How to understand StringBuffer is thread-safe and StringBuilder is non-thread-safe in Java?
- How do we compare String in Java
- What is the difference between String, StringBuffer and StringBuilder classes in Java explain briefly?
- Can we compare numbers in a MySQL varchar field?
- How can we compare data in two MySQL tables?
- How do we compare two arrays in Java?
Advertisements