What is String concatenation? I'm not so calm.

Source: Internet
Author: User

Recently, I am reading the old projects written by others.CodeWhen I found three places that made me very unaccustomed and uncomfortable. One is that the probability of select * appears in SQL query statements is extremely high, and the other is that when the entity is converted, it needs to be traversed and converted by hand, the last one is that they use a large area of String concatenation in the project. The first two problems indicate that the project development automation is not enough. The latter is a bit humorous, and it proves that String concatenation is a popular programming method. For code perfectionists, a large number of String concatenation must be unable to escape the fate of refactoring, but since it is already spectacular in the project, I have no better way to worship it, we cannot change it too far.

1. The emergence of stringjoiner

For this String concatenation, both C # and Java have corresponding improved classes and methods. For example, we are familiar with the stringbuilder class under C #, the string format method, and does Java also have the stringbuffer class? However, in actual development, many people prefer to add strings directly. replace also appears several times in a timely manner to improve their exposure. Although code writing is easy, the readability is not so bad strictly, and the running performance is not outrageous, after the event, maybe the person who writes the code will be able to clean up the gold and silver and leave the house. This code may be used in many projects, both large and small ...... It happened that the person who maintained the code was very angry. After thinking of a good solution and holding his nose angry and restructuring the inefficient code, the promotion of the selfless sharing style was posted in the garden for the benefit of the public, accidentally becoming a pioneer in "saving those low-performance string assembly code", coolcode, I'm right?

For more information about stringjoiner's past and present, see the masterpiece of coolcode:

Stringjoiner saves the poorly performing string assembly code

 

2. You can add a few more basic methods. You can name them and try again.

In the original text of my friend coolcode, He didn't post all the source code. When I use it in projects, I think I can add several common methods, such as the replace, remove, and clear methods, because they are frequently used. At the same time, we can also take into account the class of "common sense". Maybe one day everyone thinks this is a good thing, and then we will use it in a large area to replace string or stringbuilder. Isn't it possible? So we can also get the static string format method, the append method of stringbuilder and the appendformat instance method.

For example, the format static method can be defined as follows:

 
Public static stringbuffer format (string format, object arg0) {stringbuffer sb = new stringbuffer (); sb. Builder. appendformat (format, arg0); return sb ;}

The append and appendformat of the two instance methods are rarely used for reconstruction of direct String concatenation. It seems that there is no need to write them in (the two instance methods are not useless, depending on project needs, I can comment out the extension method, I add). Fortunately, we still have the extension method:

//< summary> /// stringbuffer extension ///  Public static class stringbufferextension {public static stringbuffer append (this stringbuffer Sb, string input) {sb. builder. append (input); // Sb + = input; return sb;} public static stringbuffer append (this stringbuffer Sb, object input) {sb. builder. append (input); // Sb + = input; return sb;} public static stringbuffer appendformat (this stringbuffer Sb, string format, Params object [] ARGs) {sb. builder. appendformat (format, argS); return sb ;}

The name of this stringjoiner is not very close to the public. Didn't the stringbuffer class in Java be mentioned above? In addition to coolcode, which of the following naming conventions can be used )? This article usesStringbufferClass Name, which can be seen in the demo, is not to say that stringjoiner is not good. To be honest, this is one of the most localized names I have ever seen. Thanks again for coolcode's selfless contribution. In actual project development and maintenance, this category has not been saved twice.

 

Finally, download the demo: stringbuffer

 

ReferenceArticle:

Http://www.cnblogs.com/coolcode/archive/2009/10/13/StringJoiner.html

Http://blog.zhaojie.me/2009/11/string-concat-perf-1-benchmark.html

Http://blog.zhaojie.me/2009/12/string-concat-perf-3-profiling-analysis.html

 

Appendix: Be careful when there are two types of exceptions: outofmemory and stackoverflow.

In the last few nights, I will review the <CLR via C #> Chapter on exception and status management. In addition to common exceptions such as null reference, parameter, and index out-of-bounds, the book also mentions outofmemory and stackoverflow exceptions, although these two exceptions are unlikely to occur in actual projects.

I. "insufficient memory"

An outofmemoryexception is thrown when the memory capacity exceeds the rated capacity. Why does it exceed the rated memory capacity? Very simple: the memory space is limited, but the requirement for memory allocation is unlimited (it seems thatFamous saying).

1,ProgramToo much data to be stored in memory at one time

For example, every time we fetch data from the database, if we retrieve millions or tens of millions of data each time, generally, the memory of a general PC is not very large (the maximum I have used is 4 GB ), if the structure of the retrieved data stored in the memory is a little more complex (such as dictionary with nested structure and two-way linked list), when retrieving the data for memory allocation, the first allocation fails, and the CLR throws an outofmemoryexception.

2,Or it appears that the memory is dynamically allocated multiple times in a row.

This process can be intuitively and simply understood as (strictly speaking, it is incorrect. In essence, it is true that the memory is allocated at one time, but the remaining memory space is insufficient) split the memory allocated with a large amount of data into multiple memory allocations. For example, the following program:

Stringbuffer STR = string. empty; STR + = "hello"; STR + = ""; STR + = "world"; STR + = environment. newline; For (INT I = 0; I <24; I ++) {STR + = STR;} console. writeline (STR );

We use the stringbuffer class described above to concatenate strings. During a for loop, the program concatenates a string with a geometric level (N power of 2. Therefore, if we have too many cycles, the exception of insufficient memory will occur. During the local test, my computer encountered an exception 24 times in a loop. If we know how the variable (mutable) string stringbuilder dynamically allocates memory on the managed stack, it is not hard to understand how to throw an exception here.

 

Ii. "Stack explosion"

Stackoverflowexception, which literally means "Stack burst". Speaking of this exception, we can easily think of recursion. Below is a simple code to reproduce this exception:

 class example {private string name; Public string name {get {// return name; return name; // recursive call} set {name = value;} public example () {name = "stack over flow";} static void main () {example OBJ = new example (); console. writeline (obj. name); console. read () ;}

We usually talk about recursion. We usually immediately think of recursive calls to methods. This program outputs the name attribute (the nature of the attribute is actually a method. This can be seen through Il, because we know that msil has no attribute except classes, methods, and fields) A recursive call occurs. The value of the name attribute is obtained by returning the name (actually the name should be returned) attribute in get, which leads to the acquisition of the name attribute.UnlimitedRecursive call (note that the so-called "unlimited" recursive call is literally correct, but the actual number of recursive layers is related to your computer's memory and CLR, it is certainly not an "unlimited" option ). The simplest way to avoid such exceptions is to avoid recursion (such as iteration) or optimize recursion (refer to Lao Zhao's blog) in the program as much as possible ), for recursion in this article, you only need to write the attribute correctly.

 

Refer:

Jeffrey Richter <CLR via C #>

Http://blog.zhaojie.me/2009/03/tail-recursion-and-continuation.html

Http://blog.zhaojie.me/2009/04/tail-recursion-explanation.html

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.