Memory Efficiency and Performance of String.Replace .NET Framework

前端 未结 10 1338
天命终不由人
天命终不由人 2020-11-27 16:50
 string str1 = \"12345ABC...\\\\...ABC100000\"; 
 // Hypothetically huge string of 100000 + Unicode Chars
 str1 = str1.Replace(\"1\", string.Empty);
 str1 = str1.Rep         


        
10条回答
  •  不知归路
    2020-11-27 17:10

    Here's a quick benchmark...

            Stopwatch s = new Stopwatch();
            s.Start();
            string replace = source;
            replace = replace.Replace("$TS$", tsValue);
            replace = replace.Replace("$DOC$", docValue);
            s.Stop();
    
            Console.WriteLine("String.Replace:\t\t" + s.ElapsedMilliseconds);
    
            s.Reset();
    
            s.Start();
            StringBuilder sb = new StringBuilder(source);
            sb = sb.Replace("$TS$", tsValue);
            sb = sb.Replace("$DOC$", docValue);
            string output = sb.ToString();
            s.Stop();
    
            Console.WriteLine("StringBuilder.Replace:\t\t" + s.ElapsedMilliseconds);
    

    I didn't see much difference on my machine (string.replace was 85ms and stringbuilder.replace was 80), and that was against about 8MB of text in "source"...

提交回复
热议问题