The difference between String and StringBuffer can be said to be countless on the Internet, but when I saw this article, I felt that the small examples in it were very representative, so I turned to it and made a summary myself.
There are 3 classes in java that are responsible for character operations.
1.Character operates on a single character, and
2.String operates on a string of characters. Immutable classes.
3.StringBuffer also operates on a string of characters, but it is a variable class.
String:
is an object that is not a primitive type.
is an immutable object. Once it is created, its value cannot be modified.
Any modification to an existing String object is to create a new object and then add the new one. The value is saved in.
String is a final class, that is, it cannot be inherited.
StringBuffer:
is a mutable object. When it is modified, the object will not be re-established like String.
It can only be created through the constructor ,
StringBuffer sb = new StringBuffer();
note: It cannot be paid through the value symbol.
sb = "welcome to here!";//error
After the object is created, memory will be allocated in the memory space, and initially saves a null. When paying value to StringBuffer
, you can use its append method.
sb.append("hello");
StringBuffer is more efficient than String in string connection operations:
String str = new String("welcome to ");
str += "here"; The processing steps of
are actually to create a StringBuffer, let you call append(), and finally
then convert StringBuffer toSting();
like this In this case, String's connection operation requires some additional operations than StringBuffer, but of course the efficiency will be compromised.
And since the String object is an immutable object, a new object will be re-established every time Sting is operated to save the new value.
This way The original object is useless and will be garbage collected. This will also affect performance.
Look at the following code:
Added 26 English letters 5000 times,
1. String tempstr = "abcdefghijklmnopqrstuvwxyz" ;
2. int times = 5000;
3. long lstart1 = System.currentTimeMillis();
4. String str = "";
5. for (int i = 0; i 6 . str += tempstr;
7. long lend1 = System.currentTimeMillis(); The computer is not a supercomputer, and the result obtained may not be the same every time, usually around 46687.
That’s 46 seconds.
Let’s take a look at the following code again
1. String tempstr = "abcdefghijklmnopqrstuvwxyz";
2. int times = 5000;
3. long lstart2 = System.currentTimeMillis();
5. for (int i = 0; i 6. sb.append(tempstr);
7. long lend2 = System.currentTimeMillis();
9. long time2 = ( lend2 - lstart2);
10. System.out.println(time2);
The result is 16 and sometimes 0
So the conclusion is obvious, StringBuffer is almost tens of thousands times faster than String. Of course this data is not very accurate. Because when the number of cycles is 100,000, the difference is even greater. If you don’t believe me, try it.
According to the above:
The processing step is actually to create a StringBuffer, let you call append(), and finally
then StringBuffer toSting();so str += "here"; can be equivalent to
StringBuffer sb = new StringBuffer(str);
1. String tempstr = "abcdefghijklmnopqrstuvwxyz";
2. int times = 5000;
3. long lstart2 = System.currentTimeMillis(); int i = 0; i 6. StringBuffer sb = new StringBuffer(str);
7. sb.append(tempstr);
8. str = sb. long lend2 = System.currentTimeMillis();
11. long time2 = (lend2 - lstart2);
12. System.out.println(time2);
The average execution time is about 46922, which is 46 seconds.
Summary: If you need to frequently modify and connect strings in your program, the performance will be higher using StringBuffer

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
