Talk about what some of the string concatenation of thing

String programmer for me is meeting a day when a string regulars, you do not know he is not unfamiliar with the line, string concatenation is commonplace, then realized in the actual development process in which there are a number of string concatenation way? Let's work together to talk, to communicate, to learn a wave. Perhaps you will say, that's too simple Well, who would not ah, ha ha, really simple to use, but not necessarily the way we use the best way there right?

    Before the article, we briefly talk about the type of data stored string must understand the concept:

    string is a reference type, is a sealed class, stored on the heap, every new changes will create a new string to store the original will be automatically recovered. This is not the feeling is nonsense, everyone knows Well, ha ha ha.

    Mosaic of following four common ways string: below to c # language will be described for the development of

 

First, directly through the stitching +

 

    Directly through the stitching is our code + the most common way, following a simple piece of code to analysis

    string str="1";

    str=str+"2";

    First code, a first memory space allocated to store str variable whose value is "1"

    The second paragraph of the code, reassign a new memory space to store "12", and will point to the new address str

    Through analysis, we find that in fact, on both ends of simple code, there will be twice the memory address of the operation, with the number of address string concatenation, the number of allocated memory address is also incremented when a few simple string when splicing by the way, in fact, we still feel not affect performance, but when a large number of strings, you will have a feeling, that memory is not only wasteful, but also directly affect the performance.

So in actual development projects, by + string concatenation relatively common, but if you just saw in this way is also not so friendly, and since unfriendly, then obviously there will be more friendly manner friends, here we analysis to implement string concatenation by StringBuilder.

 

Second, by stitching string StringBuilder

 

    StringBuilder fact is a character array corresponding to an internal maintenance can dynamically increase a length of the data itself, the default length of 16, when the stored character string exceeds the length is twice the length of the expansion automatically.

    Haha, Speaking of which, guess you see a problem, and that is beyond the length of automatic expansion, automatic expansion is not it also need to sacrifice performance, of course, several expansion Do you still feel not affect performance, but if the number of words more, you will feel obviously, this is also the StringBuilder some tips.

We went to different junior partner of the code, you will find that technology veterans, initializing StringBuilder time will be stored according to estimates of the size of the string, to initialize a StringBuilder length, which is reflected in the gap on the details.

    He said a half-day nonsense, is not to come to the actual code to prove not talking nonsense it? And not be anxious, in the last article, I will specifically write test code comparative analysis.

 

Third, string.Format not familiar with it

 

    For data registration fill in some format, string.Format is often seen, he's a big advantage is, looks relatively clear

    In fact, we have seen the realization of the underlying string we will find that the underlying essence is to achieve StringBuilder

    Here is the source code to achieve string.format

public static String Format(IFormatProvider provider, String format, params Object[] args) <br>{

    if (format == null || args == null)

      throw new ArgumentNullException((format==null)?"format":"args");

    StringBuilder sb = new StringBuilder(format.Length + args.Length * 8);

    sb.AppendFormat(provider,format,args);

    return sb.ToString();

}
 

 

    In fact string.Format is simple to use, I will not in the long-winded introduction, so we feel tired, ha ha ha

    string result = string.Format ( "Hello everybody, my name is {0}, {1} this year", "Pragmatic Programmer Tour", 1);

 

Fourth, $ mode string concatenation

 

    C # 6.0 there was $ string concatenation way, in fact, it simply is string.Format streamline operations version, string.Format if too many string concatenation is estimated to rip themselves forced to tell a correspondence relationship, in case you do not know to live without, anyway, I had encountered before. $ On a good circumvent this problem, the next example shows a face to everything:

    

    string name = "程序员修炼之旅";    int age = 1;    string str = string.Format("my name is{0}, I'm {1} years old",name,age);    string str2 = $"my name is{name}, I'm {age} years old";    最终结果是:str=str1

 

Fifth, of course, there are other ways, not in this long-winded, and follow-up discussion

 

test analysis

    Said a long time, not something to get some actual test, I know you are not convinced, following directly on the test code:

using System;
using System.Diagnostics;
using System.Text;

namespace stringSplicingTest
{
    ///  <Summary> 
    /// string concatenation practice
     ///  </ Summary> 
    public  class Program
    {
        /// <summary>
        /// 主函数入口
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // test StringBuilder respectively connected to the 100 numbers 0 through + 
            Console.WriteLine ( " and connected to the test respectively StringBuilder + " );
            Console.WriteLine("");
            Console.WriteLine ( " Test Connection 0 - 100 number " );
            Console.WriteLine("");
            Plus String ( 100 );
            StringBuilderString2(100);
            Console.WriteLine("");

            Console.WriteLine("");
            Console.WriteLine ( " Test Connection 0--10000 number " );
            Plus String ( 10000 );
            StringBuilderString2(10000);
            Console.WriteLine("");
            Console.WriteLine("");

            // The following test is also connected StringBuilder string, is defined to eat a specified length, a comparison is not specified length 
            Console.WriteLine ( @ " The following test is also connected StringBuilder string, is defined and a specified length, is a Comparative length is not specified " );
            Console.WriteLine("");
            Console.WriteLine ( " Test Connection from 0 - 1,000,000 " );
            Console.WriteLine ( " not initialize length " );
            StringBuilderString(1000000);
            Console.WriteLine ( " Initialization length " );
            StringBuilderString2(1000000);

            Console.WriteLine("");
            Console.WriteLine("");

            Console.WriteLine ( " Test Connection 0 - 10,000,000 number " );
            Console.WriteLine ( " not initialize length " );
            StringBuilderString(10000000);
            Console.WriteLine ( " Initialization length " );
            StringBuilderString2(10000000);

            Console.ReadLine();
        }

        ///  <Summary> 
        /// by string concatenation +
         ///  </ Summary> 
        ///  <param name = "totalnum"> </ param> 
        Private  static  void PlusString ( int totalnum)
        {
            /// / define a stopwatch, the implementation of access execution time 
            The Stopwatch ST = new new The Stopwatch (); // instantiate class 
            st.Start (); // start timing 

            Console.WriteLine ( " started, the connection string of +: " );
             String Result = "" ;
             /// / define an array 
            for ( int I = 0 ; I <totalnum; I ++ )
            {
                result = result + i.ToString();
            }

            // need to count the time code segment 

            st.Stop (); // termination timing 
            Console.WriteLine ( String .Format ( " finished, the connection string of + {0} milliseconds total time! " ,
            st.ElapsedMilliseconds.ToString()));
        }

        ///  <Summary> 
        /// by splicing string s
         ///  </ Summary> 
        ///  <param name = "totalnum"> </ param> 
        Private  static  void StringBuilderString ( int totalnum)
        {
            /// / define a stopwatch, the implementation of access execution time 
            The Stopwatch ST = new new The Stopwatch (); // instantiate class 
            st.Start (); // start timing 

            Console.WriteLine ( " started, a string which connects the StringBuilder: " );

            StringBuilder result = new StringBuilder();

            /// / define an array 
            for ( int I = 0 ; I <totalnum; I ++ )
            {
                result.Append(i.ToString());
            }

            String result2 = result.ToString ();
             // need to count the time code segment 

            st.Stop (); // termination timing 
            Console.WriteLine ( String .Format ( " finished, a string which connects StringBuilder total time {0! } ms " ,
            st.ElapsedMilliseconds.ToString()));
        }


        ///  <Summary> 
        /// by splicing StringBuilder string, specifying a length initialization
         ///  </ Summary> 
        ///  <param name = "totalnum"> </ param> 
        Private  static  void StringBuilderString2 ( int totalnum)
        {
            /// / define a stopwatch, the implementation of access execution time 
            The Stopwatch ST = new new The Stopwatch (); // instantiate class 
            st.Start (); // start timing 

            Console.WriteLine ( " started, a string which connects the StringBuilder: " );

            StringBuilder result = new StringBuilder(totalNum * 6);

            /// / define an array 
            for ( int I = 0 ; I <totalnum; I ++ )
            {
                result.Append(i.ToString());
            }

            String result2 = result.ToString ();
             // need to count the time code segment 

            st.Stop (); // termination timing 
            Console.WriteLine ( String .Format ( " finished, a string which connects StringBuilder total time {0! } ms " ,
            st.ElapsedMilliseconds.ToString()));
        }
    }
}

 

 

 

Analyze and summarize the results:

Test two points:

One test is: + and by comparing the performance of StringBuilder string concatenation oh

The second test is: performance comparison StringBuilder not initialize the length and the length of the initialization

Probably draw the following conclusions

1, when a character string to be spliced ​​less, + and no significant performance difference StringBuilder

2, when a long string stitching, StringBuilder advantage more and more obvious

3, the same string StringBuilder splicing efficiency than the estimated length of the initialization is not efficient to initialize the specified length

Having said this, I believe we all know how to use. Well, the hour is late, and quickly wash sleep, tomorrow have to go to work?

 END

 

 
Welcome all partners concerned about the small number of my public (programmer practice tour), which will share some technology like dry goods, but also a technical communication platform, thank you for your support.

 

Guess you like

Origin www.cnblogs.com/xiaoXuZhi/p/XYH_String2.html