String combination and complexity?

When I need to join two strings, I use String.Format (or StringBuilder if this happens in several places in the code).

I see that some good programmers do not pay attention to the complexity of the lines and simply use the "+" operator.

I know that using the + operator causes the application to use more memory, but what about complexity?

+4
source share
12 answers

This is a great article on the different methods of combining strings of our own Jeff Atwood about Coding Horror :

alt text
(source: codinghorror.com )

.

[ ]

. ?

? !

.. ..

. . . !

+9

, .

+ , , . , , , O (n ^ 2).

, , :

string foo = "a";
for(int i = 0; i < 1000; i++)
{
    foo += "a";
}

, foo ( "a" ) , "a" . . ; foo "a" . 1000- 1001 . 2 + 3 + ... + 1001. , ( ), n, 2 + 3 + ... + n + 1 . , 1 + 2 + 3 + ... + n = n(n+1)/2 = (n^2 + n)/2, O (n ^ 2).

+4

. + . :

output = "<p>" + intro + "</p>";

, . String.Format.

+1

+ , , ( ).

, : ( ).

, + ( , 2 . "<p>" , "</p>" .

, . , , , intro - .

+1

, . axample "A" + "B" + "C" + "D" , "A", "AB" , , "ABC", "ABCD". - , ? , , , 1000 , , (1000 + N) 1000 . O (n ^ 2) .

Strin.Fomat, , StringBuffer O (n).

+1

StringBuilder , . , , , . +, ( )

+1

(, , !), . .

+1

, Java #, , , , .

, , c.

2 * c , n-1, (n-1) * c , , c , n * c. n n ^ 2 * c/2 , O (n ^ 2).

, , ( , . ), .

, , O (n ^ 2) .

, , Word XML , base64. 10 - O (n ^ 2). , + StringBuilder, 10 .

, , SQL , + . , ( ), StringBuilder. .

, , / , , : -)

+1

: "a" + "b" + "c" String.Concat( String.Format )

0

, , - , , , .

, Big O, , , ( , ), . strA + strB strA.Append(strB) 100 000 , , .

0

. :

string s = "a" + "b" + "c";

:

string s = "abc";

. MSDN.

0

, .NET 1.0 1.1.

Then, if you had some kind of process that was about to hit a line of code that would be a concatenating string several million times, you could get a huge speed increase with String.Concat, String.Format or StringBuilder.

Now it does not matter. At least it didn't matter, since .Net 2.0 came out anyway. Take it out of your mind and code to make it easier for you to read.

0
source

Source: https://habr.com/ru/post/1715992/


All Articles