This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
preface
StringBulider: StringBuffer: StringBuffer: StringBuffer: StringBuffer: StringBuffer: StringBulider: StringBuffer: StringBuffer: StringBuffer
Fix: The myth from the last post
Last time I talked about how String can be faster than StringBuilder in some cases, which is not true, and how StringBuilder memory modifications cost money. These are not true. The reason why String is slow is because it constantly opens up space. In Java, it takes time to open up memory space. This can be tested in the cumulative consumption of multiple concatenation strings. I tested StringBuilder in 0.008 seconds while String took over 0.64 seconds. However, The reason why StringBuilder is fast is that it is always an object operation and does not generate excessive memory fragmentation. A large number of String concatenation will generate a large amount of memory fragmentation, which increases the chances of GC. Therefore, String concatenation is not recommended.
StringBuffer
Stringbuffers are awkward because they are rarely or never used in business logic. The StringBuffer was developed because Sun thought that they could not watch String stitching because of cerebral palsy, so they withdrew StringBuffer to replace String stitching and added thread safety to String stitching. Causing his extra expenses to become bloated. StringBuffer was born earlier than StringBuilder, but after Buffer came out, Sun Realized that thread-safe concatenation of strings was very rare in development, so StringBuilder was developed as a non-thread-safe string concatenation. Without the multithreaded safety constraints, StringBuilder can be incredibly fast. After Java 1.5, the Java compiler compiles bytecode files and optimizes String + sign concatenation into StringBuilder. But the + sign in the for loop is replaced with multiple New StringBuilders, so it’s good to get into the habit of concatenating strings with StringBuilder in any case.
conclusion
- StringBuiler is greater than StringBuffer is greater than String execution speed
- One point I forgot to mention above is that all three classes are final