[Mono-dev] [Patch] Small optimization to String.Replace and StringBuilder.Replace

Andreas Nahr ClassDevelopment at A-SoftTech.com
Mon Jun 16 13:20:03 EDT 2008


Did you time/measure this change?

-			const int maxValue = 200; // Allocate 800 byte
maximum
+			// Allocate 800 byte maximum
+			int maxValue = Math.Min ((length + oldValue.Length -
1) / oldValue.Length, 200);
 			int* dat = stackalloc int[maxValue];
 			fixed (char* source = this, replace = newValue) {
 				int i = 0, count = 0;
@@ -1661,6 +1654,9 @@
 					}
 					i = found + oldValue.length;
 				}
+				if (count == 0)
+					return this;
+
 				int nlen = this.length + ((newValue.length -
oldValue.length) * count);
 				String tmp = InternalAllocateStr (nlen);

My assumption is that for small (common) cases this may produce a noticable
slowdown.
I'm fine with the count == 0 shortcut, but the exact calculation will
probably hurt performance.
Maybe a compromise would be
int maxValue = Math.Min (length, 200);

Happy Hacking
Andreas

> -----Ursprüngliche Nachricht-----
> Von: mono-devel-list-bounces at lists.ximian.com [mailto:mono-devel-list-
> bounces at lists.ximian.com] Im Auftrag von Juraj Skripsky
> Gesendet: Montag, 16. Juni 2008 16:38
> An: mono-devel
> Betreff: [Mono-dev] [Patch] Small optimization to String.Replace and
> StringBuilder.Replace
> 
> Hello,
> 
> Attached you'll find a patch which reduces the number of allocations
> done in String.Replace and StringBuilder.Replace.
> 
> All unit tests pass.
> Please review.
> 
> - Juraj



More information about the Mono-devel-list mailing list