See the first scenario: Use a string to connect to the database for 10 thousand times.
Public class demo_01 {public static void main (string [] ARGs) {string STR = "123"; string [] temp = new string [10000]; for (INT I = 0; I <temp. length; I ++) {temp [I] = "456";} long begin = system. nanotime ()/000000l; system. out. println (BEGIN); For (INT I = 0; I <temp. length; I ++) {STR + = temp [I];} long end = system. nanotime ()/000000l; system. out. println (end); system. out. println ("connection operation time consumed:" + (end-begin) + "millisecond ");}}
Compile and execute
The same string connection is also connected 10 thousand times this time using stringbuilder
Public class demo {public static void main (string [] ARGs) {stringbuilder sb = new stringbuilder (); sb. append ("123"); string [] temp = new string [10000]; for (INT I = 0; I <temp. length; I ++) {temp [I] = "456";} long begin = system. nanotime ()/000000l; system. out. println (BEGIN); For (INT I = 0; I <temp. length; I ++) {sb. append (temp [I]);} long end = system. nanotime ()/000000l; system. out. println (end); system. out. println ("connection operation time consumed:" + (end-begin) + "millisecond ");}}
Compile and execute
The time consumed by the comparison execution. String is 479 Ms. stringbuilder is 2 ms. (The number of milliseconds is for reference only. Different PC configurations and OS environment factors may vary)
When using stringbuilder for the same string connection operation, you only need to use about 1/240 of the string.
It can be seen that stringbuilder is more efficient when a large number of string connections are made.
Anyone who has learned Java knows this. You can use it.
But why is stringbuilder more efficient when a large number of string connections are made?
This is a question worth thinking about.
Well, let's take a look at the feedback from the compiler.
For string-based connection, use the disassembly command
Obtain the following information:
We can see that 79 rows of goto statements point to 47 rows, which is a loop body.
Hmm? I use a string, but in fact the compiler is good at making claims using stringbuilder for connection operations. (Stringbuilder is highly efficient)
Note that 54 rows will create a new stringbuilder object each time.
Let's look at the operations using stringbuilder:
Feedback
Note that 78 rows of goto statements point to 59 rows.
However, this loop body only has one stringbuilder object. The compiler does not create a new stringbuilder object every cycle.
Therefore, stringbuilder is more efficient in connection with a large number of strings than string.
The next section will discuss the reasons why stringbuilder is more efficient from the source code perspective.