Advertisement
Guest User

Untitled

a guest
May 24th, 2015
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.01 KB | None | 0 0
  1. program TestString;
  2.  
  3. {$APPTYPE CONSOLE}
  4.  
  5. uses
  6.   Diagnostics,
  7.   SysUtils;
  8.  
  9. {$UNDEF REUSE_STRING}
  10. {$DEFINE REUSE_STRING}
  11.  
  12. type
  13.   TTest = procedure;
  14.  
  15. const
  16.   dwBufferLen = 10000;
  17.  
  18. var
  19.   lpBufferPos, lpStart: PChar;
  20.  
  21. {$IFDEF REUSE_STRING}
  22. var
  23.   s: string;
  24. {$ENDIF}
  25.  
  26. procedure CallMove;
  27. var
  28.   len: Integer;
  29. {$IFNDEF REUSE_STRING}
  30.   s: string;
  31. {$ENDIF}
  32. begin
  33.   len := lpBufferPos - lpStart;
  34.   SetLength(s, len);
  35.   Move(lpStart^, s[1], len * SizeOf(Char));
  36. end;
  37.  
  38. procedure CallMoveMod;
  39. var
  40.   len: Integer;
  41. {$IFNDEF REUSE_STRING}
  42.   s: string;
  43. {$ENDIF}
  44. begin
  45.   len := lpBufferPos - lpStart;
  46.   SetLength(s, len);
  47.   Move(lpStart^, Pointer(s)^, len * SizeOf(Char));
  48. end;
  49.  
  50. procedure CallSetString;
  51. {$IFNDEF REUSE_STRING}
  52. var
  53.   s: string;
  54. {$ENDIF}
  55. begin
  56.   SetString(s, lpStart, lpBufferPos - lpStart);
  57. end;
  58.  
  59. procedure Test(const test: TTest);
  60. const
  61.   max = 5000000;
  62. var
  63.   idx: Integer;
  64.   lpInput: PChar;
  65.   swTimer: TStopwatch;
  66. begin
  67.   swTimer := TStopwatch.Create();
  68.   lpInput := StrAlloc(dwBufferLen);
  69.   try
  70.     // this will have a distance of 40% of the length of the buffer between
  71.     //  the start and the position in the buffer.
  72.     // example:
  73.     //  if dwBufferLen is 1000, the copied string will be 400 characters long,
  74.     lpBufferPos := lpInput;
  75.     Inc(lpBufferPos, dwBufferLen div 2);
  76.  
  77.     lpStart := lpInput;
  78.     Inc(lpStart, dwBufferLen div 10);
  79.  
  80.     swTimer.Start;
  81.     for idx := 1 to max do
  82.       test();
  83.     swTimer.Stop;
  84.  
  85.     Writeln('Ticks ', swTimer.ElapsedTicks);
  86.   finally
  87.     StrDispose(lpInput);
  88.   end;
  89. end;
  90.  
  91. begin
  92. {$IFDEF REUSE_STRING}
  93.   Writeln('output string will be reused');
  94.   Writeln;
  95. {$ENDIF}
  96.  
  97.   Writeln('SetLength & Move');
  98.   Test(CallMove);
  99.   // 9396476 with reuse
  100.   // 9918661 without reuse
  101.  
  102.   Writeln('SetLength & Move modified');
  103.   Test(CallMoveMod);
  104.   // 9368567 with reuse
  105.   // 9866585 without reuse
  106.  
  107.   Writeln('SetString');
  108.   Test(CallSetString);
  109.   // 9601162 with reuse
  110.   // 9842723 without reuse
  111.  
  112.   Readln;
  113. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement