Use StringBuilder more

xiaoxiao2021-03-06  30

If you want to operate a growing string, please don't use the String class anymore. Why is it to say this? Let's take a look at the working principle of two classes.

The String class is a traditional way of modifying a string that does not mean that you can add a string to another string. But under the .NET framework, this operation is not a way. Because the system first writes two strings into memory, then delete the original String object, then create a String object and read the data in the memory to the object. This is going to go, it takes a lot of time.

The StringBuilder class under the namespace using System.Text Namespace is not the case. It provides the Append method that can make a string to modify, simple and direct in the original object.

Of course, in general, you can't assume the difference in efficiency, but if you want to add a lot of add actions to a string, the time and String class spending with the StringBuilder class are not an order of magnitude. Here is an example, you will try it yourself:

Imports SystemImports System.Text

Namespace StringBuildersample

Class ClsstrBuilder

Shared Sub Main () DIM I AS INTEGER DIM StartTime As DateTime Dim Stoptime AS DateTime

'Use string class to connect strings Console.Writeline ("String Class") DIM STR AS STRING = String.empty StartTime = DATETIME.NOW Console.writeline ("Start Time:" & StartTime.toString ()) for i = 0 to 99999 str & = i.tostring () Next I stoptime = datetime.now console.writeline ("End Time:" & stoptime.toString ())))

'Use the StringBuilder class to connect the string console.writeline ("StringBuilder class") Dim Builder as new stringbuilder () StartTime = DATETIME.NOW Console.writeline ("Start Time:" & StartTime.toString ()) for i = 0 to 99999 Builder.Append (I.toTRING ()) Next I stoptime = datetime.now console.writeline ("End Time:" & stoptime.toString ()) End Sub

END CLASS

End Namespace

转载请注明原文地址:https://www.9cbs.com/read-64963.html

New Post(0)