. NET face question 4

Source: Internet
Author: User
Tags explode

Common Interview Topics:

1. Is the string a reference type or a value type?

2. What is the best way to use string connection processing, and what is the rationale?

3. What are some issues to be aware of when using StringBuilder?

4. How many strings will be present in memory when the following code executes? What's the difference? What is the output of the result? Why is it?

String st1 = "123" + "abc"; string st2 = "123ABC"; Console.WriteLine (St1 = = St2); Console.WriteLine (System.Object.ReferenceEquals (St1, st2));

5. How many strings will be present in memory when the following code executes? What's the difference? What is the output of the result? Why is it?

string S1 = "123"; string s2 = S1 + "abc"; string s3 = "123ABC"; Console.WriteLine (s2 = = s3); Console.WriteLine (System.Object.ReferenceEquals (S2, S3));

6. Use C # to implement the string inversion algorithm, for example: Enter "12345" and Output "54321".

7. The following code outputs the result? Why?

Object A = "123"; object B = "123"; Console.WriteLine (System.Object.Equals (A, b)); Console.WriteLine (System.Object.ReferenceEquals (b)); string sa = "123"; Console.WriteLine (System.Object.Equals (A, SA)); Console.WriteLine (System.Object.ReferenceEquals (A, SA));
Easy-to-do string manipulation

String is a special type of reference that is used somewhat like a value type. Special, but also mainly because the string is too common, in order to improve performance and development convenience, the string did a special treatment, given a number of special features. To compensate for some of the performance problems with string connection operations, there is a StringBuilder.

Recognize string

First, it needs to be clear that string is a reference type whose object values are stored in the managed heap. Inside the string is a char collection whose length is the number of characters in the char array. String does not allow the creation of an instance using new string (), but rather a simpler syntax, which is directly assigned (string Aa= "000" is similar to a value type).

To recognize string, start with a simple sample code:

public void Dostringtest () {    var AA = "$";    SetStringValue (AA);    Console.WriteLine (AA);} private void SetStringValue (String aa) {    AA + = "111";}

上面的输出结果为“000”。

With the previous value type and the reference type of the article, we know that the string is a reference type, and since it is a reference type, the parameter is passed the reference address, so why not output "000111"? is not a very valuable type of features it! The reason for all this stems from two important features of the string type: constancy and dwell

The constant of string (invariance)

The string is immutable, and once created, the string will not change, and any change will result in a new string. For example, the following code, which creates a string s1= "a" on the heap, and a string "B", will have three string instances on the heap, as shown in.

string S1 = "a"; string s2 = S1 + "B";

The preceding "Any change will produce a new string", including some manipulation functions of the string, such as str1. Tolower,trim (), Remove (int startIndex, int count), ToUpper (), and so on, will produce new strings, so in many programming practices, the comparison of the size of the string ignores:

if (str1. ToLower () ==str2. ToLower ())//This method produces a new string, not recommended if (string. Compare (Str1,str2,true))//better performance in this way
The dwell of string

Because of the invariant character of strings, a large number of string objects are created, resulting in a significant performance penalty when a large number of string operations are used. So the CLR also gives string another magic weapon, that is, the string resides, first look at the following code, the string S1, S2 unexpectedly is the same object!

var S1 = "123"; var s2 = "123"; Console.WriteLine (System.Object.Equals (S1, S2));  Output Trueconsole.writeline (System.Object.ReferenceEquals (S1, S2));  Output True

The same string is allocated only once in memory (heap), and the second time a string is requested, it is found that the string is already the address of the existing string, which is the basic process of residing.

The basic principle of string residency:
    • CLR initialization creates a resident pool in memory, which is actually a hash table that stores the string that resides and its memory address.
    • A resident pool is a process-level, multiple AppDomain share. At the same time she is not under GC control, life cycle with the process, meaning is not recycled by GC (not recycled!) Doesn't it cause memory to explode? Don't worry, and see below)
    • When a string is allocated, it is first found in the resident pool, and if it finds one, returns an address that already has the same string and does not create a new string object. If it is not found, a new string is created and the string is added to the resident pool.

If a large number of strings reside in memory and are not released, is it not easy to cause memory to explode, of course not? Because not any strings will reside, only ldstr strings created through the IL directives will be retained.

There are several ways to create a string, such as the following code:

var S1 = "123"; var s2 = s1 + "abc"; var s3 = string. Concat (s1, S2); var s4 = 123.ToString (); var s5 = S2. ToUpper ();

Its IL code is as follows

In the above code, there are two string constants, "123" and "ABC", this two constant string in the IL code is created through the IL Directive ldstr , only the string created by the instruction will be resident, other ways to produce a new string will not be resident, will not share the string, will be properly recycled by GC.

So how do you verify that a string resides, and the string class provides two static methods:

    • String.intern (String str) can actively host a string;
    • string.isinterned (String str), detects whether the specified string resides, returns a string if it resides, or returns null

Take a look at the sample code below

var S1 = "123"; var s2 = s1 + "abc"; Console.WriteLine (S2);   Output: 123abcconsole.writeline (String. isinterned (S2)?? "NULL");   Output: NULL. Because "123ABC" does not host a string. Intern (S2);   Active resident String Console.WriteLine (string. isinterned (S2)?? "NULL");   Output: 123ABC

Meet StringBuilder

A large number of programming practices and opinions, all of which say a lot of string connection operations, should use StringBuilder. As opposed to a string immutable, StringBuilder represents a mutable string, does not resemble a string, and frequently allocates new objects on the managed heap, StringBuilder is a good comrade.

First, StringBuilder internally, like a string, has a char[] character array, which is responsible for maintaining the string contents. Therefore, there are two important properties related to the char array:

    • The capacity of the public int capacity:stringbuilder is actually the length of the character array.
    • The length of the actual character in public int length:stringbuilder, >=0,<= capacity capacity.

The main reason why StringBuilder is more efficient than string is that it does not create a large number of new objects, and StringBuilder assigns new objects in the following two scenarios:

    • When appending a string, when the total length of the character exceeds the current set of capacity capacity, this time, a larger character array is recreated, which involves assigning a new object.
    • Call Stringbuilder.tostring () to create a new string.
The process of appending a string:
    • The default initial capacity of StringBuilder is 16;
    • When appending a string with stringbuilder.append (), a larger character array is automatically applied when the number of characters is greater than 16,stringbuilder, which is generally multiplied;
    • After the new character array is allocated, the characters in the original character array are copied to the new character array, and the original character array is ruthlessly discarded (it will be recycled by GC);
    • Finally append the string to the new character array;

Simply put, when the StringBuilder capacity capacity changes, it will cause the managed object request, memory replication and other operations, resulting in bad performance impact, so it is necessary to set the appropriate initial capacity, minimizing memory requests and object creation. The code is simple to verify:

StringBuilder sb1 = new StringBuilder (); Console.WriteLine ("Capacity={0}; Length={1}; ", SB1. Capacity, SB1. Length); Output: capacity=16;   length=0; The initial capacity is SB1.    Append (' A ', 12); Append 12 characters Console.WriteLine ("Capacity={0}; Length={1}; ", SB1. Capacity, SB1. Length); Output: capacity=16;  length=12; SB1.    Append (' A ', 20); Continue to append 20 characters, the capacity multiplied by Console.WriteLine ("Capacity={0}; Length={1}; ", SB1. Capacity, SB1. Length); Output: capacity=32;  length=32; SB1.    Append (' A ', 41); Append 41 characters, new capacity =32+41=73console.writeline ("capacity={0}; Length={1}; ", SB1. Capacity, SB1. Length); Output: capacity=73;  length=73; StringBuilder SB2 = new StringBuilder (80); Set an appropriate initial capacity of Console.WriteLine ("Capacity={0}; Length={1}; ", SB2. Capacity, SB2. Length); Output: capacity=80; LENGTH=0;SB2. Append (' A ', 12); Console.WriteLine ("Capacity={0}; Length={1}; ", SB2. Capacity, SB2. Length); Output: capacity=80; LENGTH=12;SB2. Append (' A ', 20); Console.WriteLine ("Capacity={0}; Length={1}; ", SB2. Capacity, SB2. Length); Output: capacity=80; LENGTH=32;SB2. Append (' A', 41); Console.WriteLine ("Capacity={0}; Length={1}; ", SB2. Capacity, SB2. Length); Output: capacity=80; length=73;

Why does a small number of strings not recommend the use of StringBuilder? Because StringBuilder itself has a certain overhead, a small number of strings are deprecated, and using String.Concat and String.Join is more appropriate.

Efficient use of strings
    • When using the thread lock, do not lock a string object, because the presence of the string may cause unexpected problems;
    • Understand the immutability of strings and try to avoid generating extra strings, such as:
if (str1. ToLower () ==str2. ToLower ())//This method produces a new string, not recommended if (string. Compare (Str1,str2,true))//better performance in this way
    • When handling a large number of string connections, try to use StringBuilder, when using StringBuilder, try to set an appropriate length of the initial value;
    • A small number of string connections is recommended instead of using String.Concat and String.Join.
Answer to the question: 1. Is the string a reference type or a value type?

The reference type.

2. What is the best way to use string processing, and for what reason?

A small number of string connections, using String.Concat, a large number of strings using StringBuilder, because StringBuilder performance is better, if string will create a large number of string objects.

3. What are some issues to be aware of when using StringBuilder?
    • When a small number of strings, try not to use, StringBuilder itself is a certain performance cost;
    • When a large number of strings are connected using StringBuilder, a suitable capacity should be set;
4. How many strings will be present in memory when the following code executes? What's the difference? What is the output of the result? Why is it?
String st1 = "123" + "abc"; string st2 = "123ABC"; Console.WriteLine (St1 = = St2); Console.WriteLine (System.Object.ReferenceEquals (St1, st2));

Output Result:

Truetrue

The in-memory string has only one "123ABC", the first line of code (String st1 = "123" + "ABC"; The addition of constant strings is optimized by the compiler. Because of the string dwell mechanism, two variables st1, st2 all point to the same object. The IL code is as follows:

5. How many strings will be present in memory when the following code executes? What's the difference? What is the output of the result? Why is it?
string S1 = "123"; string s2 = S1 + "abc"; string s3 = "123ABC"; Console.WriteLine (s2 = = s3); Console.WriteLine (System.Object.ReferenceEquals (S2, S3));

And the 5th question the result certainly is not the same, the answer leaves the reader, the article is too long, the writing good tired!

6. Use C # to implement a string inversion algorithm, for example: Input "12345", Output "54321"

This is a more comprehensive study of the problem of string manipulation, the answer can be many kinds. The basic level of the program ape can be seen through different answers. The following is the online comparison of the two kinds of answers, efficiency is relatively good.

public static string Reverse (String str) {    if (string. IsNullOrEmpty (str))    {        throw new ArgumentException ("argument not valid");    }    StringBuilder sb = new StringBuilder (str. Length);  Note: Setting the appropriate initial length can significantly improve efficiency (avoiding multiple memory requests) for    (int index = str.) Length-1; Index >= 0; index--)    {        sb. Append (Str[index]);    }    Return SB. ToString ();}
public static string Reverse (String str) {    if (string. IsNullOrEmpty (str))    {        throw new ArgumentException ("argument not valid");    }    char[] chars = str. ToCharArray ();    int begin = 0;    int end = chars. Length-1;    char Tempchar;    while (begin < End)    {        Tempchar = Chars[begin];        Chars[begin] = Chars[end];        Chars[end] = Tempchar;        begin++;        end--;    }    String strresult = new string (chars);    return strresult;}

There is also a simpler and more effective way:

public static string Reverse (String str) {    char[] arr = str. ToCharArray ();    Array.reverse (arr);    return new string (arr);
7. The following code outputs the result? Why?
Object A = "123"; object B = "123"; Console.WriteLine (System.Object.Equals (A, b)); Console.WriteLine (System.Object.ReferenceEquals (b)); string sa = "123"; Console.WriteLine (System.Object.Equals (A, SA)); Console.WriteLine (System.Object.ReferenceEquals (A, SA));

The output is all true because they all point to the same string instance, and there is no difference between using the object declaration and the string declaration (string is the reference type).

Is there a difference between using the object declaration and the string declaration? , a little puzzled, a friend interviewed by the interviewer asked this question, the interviewer said SA, A is a difference, and not equal. For this question, welcome to the exchange.

All rights reserved, article source: http://www.cnblogs.com/anding

Personal ability is limited, the content of this article is only for study, discussion, welcome correction, Exchange.

. NET face question 4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.