String vs StringBuilder speed

Coming from Delphiland I’ve always found String to be the same or quicker than StringBuilder, and a bit easier to use eg no create/free etc.

In Oxygene/Island StringBuilder appears to be 1000’s of times quicker… correct ?

Code:

class method play;
begin
  writeLn('starting...');

  var s  := 'this is a string to compress ';
  var sb := '';
  var i : Integer;
  var ticks : Int64;
  var ticksStart, ticksEnd : DateTime;

  //strings
  ticksStart := DateTime.UtcNow;

  for i := 0 to 10000 do
    sb :=  sb + i.ToString +  s +  ' ';

  ticksEnd := DateTime.UtcNow;
  ticks := (ticksEnd.Ticks - ticksStart.Ticks) / 1000;
  writeLn ( 'String ticks: ' + ticks.ToString + ' Size: ' + sb.Length.ToString);
  
  sb := '';
  
  //stringbuilder
  ticksStart := DateTime.UtcNow;

  var sa := new StringBuilder;
  for i := 0 to 10000 do
    sa.Append( i.ToString +  s +  ' ' );
  
  sb := sa.ToString;
  ticksEnd := DateTime.UtcNow;
  ticks := (ticksEnd.Ticks - ticksStart.Ticks) / 1000;
  writeLn ( 'Stringbuilder ticks: ' + ticks.ToString + ' Size: ' + sb.Length.ToString);
  
  //Zlib test
  writeLn('about to compress');
  ticksStart := DateTime.UtcNow;

  var aBytes : array of Byte;
  aBytes := Ionic.Zlib.GZipStream.CompressString( sb );

  aBytes.Length.ToString;
  writeLn( 'Compress ');
  writeLn( 'String ' + sb.Length.ToString );
  writeLn( 'Array  ' + aBytes.Length.ToString );

  var sb2 := '';

  sb2 := Ionic.Zlib.GZipStream.UncompressString( aBytes );
  writeLn( 'UnCompress ');
  writeLn( 'Array  ' + aBytes.Length.ToString );
  writeLn( 'String ' + sb2.Length.ToString );


  ticksEnd := DateTime.UtcNow;
  ticks := (ticksEnd.Ticks - ticksStart.Ticks) / 1000;
  writeLn ( 'Zlib ticks ' + ticks.ToString );


  if sb = sb2 then
    writeLn( 'sb = sb2 :)' )
  else
    writeLn( 'sb <> sb2 :(' );

end;

Output:

The magic happens here.
starting…
String ticks: 65880 Size: 338925
Stringbuilder ticks: 60 Size: 338925
about to compress
GzipStream
Compress
String 338925
Array 22897
GzipStream
UnCompress
Array 22897
String 338925
Zlib ticks 540
sb = sb2 :slight_smile:

1 Like

Interesting. Thank you for sharing
BTW - pardon my lack of knowledge - what is “Ionic.Zlib”? How can I get it as well?

I just ported the C# zlib to Island… Suspect I’ll git it or something soon

1 Like

And StringBuilder gets faster!!!

  var sa := new StringBuilder;
  for i := 0 to 10000 do
  begin
    //sa.Append( i.ToString +  s +  ' ' );
    sa.Append( i.ToString).Append(s).Append(' ');
  end;

50 vs 60

StringBuilder is a mutable string that resizes a bit like a memory stream (though not as drastically iirc). So yeah , for string every mutation requires an allocation and move, while for stringbuilder it just updates the buffer and length, which is going to be a lot faster (and the whole reason of string builder’s existence is that string has overhead for changing since the underlying class is immutable).