Performance when performing string concatenation - C # algorithm string strings

I used the following code to add lines

string res = string.Empty;
int ite = 100000;
for(int i= 0; i < ite; i++)
{
    res += "5";
}

This took a lot of time, so I later changed the code to

string res = string.Empty;
int ite = 100000;
res = getStr(ite / 2) + getStr(ite - (ite / 2)); 

//body of getStr method
private static string getStr(int p)
{
    if (p == 1)
        return "5";
    else if (p == 0)
        return string.Empty;
    string r1 = getStr(p / 2); //recursive
    string r2 = getStr(p - (p / 2)); //recursive  
    return (r1 + r2);
}

which, in my opinion, actually does nothing, since the number of lines connected in series is approximately the same as in the previous approach.

But using this approach, there was a significant performance improvement, since the code that took about 2500 ms (on my machine) now takes 10 ms.

I ran the processor time profiler and couldn’t understand why the performance improvement is happening. Can someone explain this.

Note. I intentionally do not use StringBuilder to understand the above.

+4
source share
2

, . , , :

someString+= "5";

someString , , 5. , , .

, , . , 8, :

"5" + "5" 
"55" + "5"
"555" + "5"
"5555" + "5"
"55555" + "5"
"555555" + "5"
"5555555" + "5"    // 7 total concatenations

:

"5" + "5"         // Four times
"55" + "55"       // twice
"5555" + "5555"   // once 

, .

, , , OP , - ; , StringBuilder, Append .

+15

- - n , . O (n 2) O (n log n), 10000 - 348: 1. O (n) Java, , -, .NET.

, c (n) , , :

c (0) = 0
  c (1) = 1
  c (n) = c (⌊n/2⌋) + c (⌈n/2⌉) + n

,

c (2 k + a) = (k + 1) 2 k + (k + 3) a

k a , n = 2 k + a, a < 2 k; . O (k 2 k), .. O (n log 2 n), O (n log n),

:

n (n + 1)/2 , , O (n 2).

; 10000 :

c (10000) =
c (2 13 + 1808) =
(13 + 1) * 8192 + 16 * 1808 =
143616

50 005 000 , 1: 348, 1: 250. , , , .

, , , , String.Substring , Java, .NET comparison-of-substring-operation-performance-between-net-and-java, ( StringBuilder String('5', ite)) , :

private static string getStr(int p)
{
    if(p == 0)
        return "";
    if(p == 1)
        return "5";
    string s = getStr ((p+1) / 2);
    if( s.Length + s.Length == p )
        return s + s;
    else
        return s + s.Substring(0, p - s.Length);
}

c 2 (n), ,

c 2 (n) = n + c 2 (⌈n/2⌉)

c 2 (n) = 2_n_ + d (n)

d (n) - -1, n 2 "" ( , ) , 0 m; , d (n) m ∈ ℕ :

d (2 m) = -1
d (2 ) = d ()
d (m) = ( ) 0 m

c 2 O (n + log n), O (n).

.

OPs c 2 (10 000) = 20 000 + d (11000011010100000 2) = 20 006 , , 7 .

  • , "5".
  • OP , , String('5', ite).
  • StringBuilder , StringBuilder(capacity).
  • , .NET.
  • C ( '\0'!), , , .
0

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


All Articles