Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // modelled after this article http://www.codeproject.com/Articles/8531/Using-generics-for-calculations
- // tried the interface approach first but the Delphi compiler does not inline the call to the implementing class
- // but rather does a very imperformant call to the interface stub method
- // since we have virtual class methods in Delphi we can use them to declare an abstract class that is used as constraint
- // see https://blogs.msdn.microsoft.com/ericgu/2003/11/14/generics-algorithms/
- program GenericsMadness;
- {$APPTYPE CONSOLE}
- {$O+,W-}
- uses
- Diagnostics;
- type
- TCalculator<T> = class
- class function Add(const a, b: T): T; virtual; abstract;
- end;
- TLists<T;C:TCalculator<T>> = class
- public
- class function Sum(const list: TArray<T>): T; static;
- end;
- TIntCalculator = class(TCalculator<Integer>)
- class function Add(const a, b: Integer): Integer; override; final;
- end;
- { TLists<T, C> }
- class function TLists<T,C>.Sum(const list: TArray<T>): T;
- var
- i: Integer;
- begin
- Result := Default(T);
- for i := 0 to High(list) do
- Result := C.Add(Result, list[i]);
- end;
- { TIntCalculator }
- class function TIntCalculator.Add(const a, b: Integer): Integer;
- begin
- Result := a + b;
- end;
- type
- TIntLists = TLists<Integer,TIntCalculator>;
- procedure Main;
- const COUNT = 10000000;
- var
- list: TArray<Integer>;
- i, n: Integer;
- sum: Integer;
- sw: TStopwatch;
- begin
- list := [1, 2, 3, 4, 5, 6, 7, 8, 9];
- sw := TStopwatch.StartNew;
- for i := 1 to COUNT do
- begin
- sum := 0;
- for n := 0 to High(list) do
- sum := sum + list[n];
- end;
- Writeln(sum, ' ', sw.ElapsedMilliseconds);
- sw := TStopwatch.StartNew;
- for i := 1 to COUNT do
- sum := TIntLists.Sum(list);
- Writeln(sum, ' ', sw.ElapsedMilliseconds);
- end;
- begin
- Main;
- Readln;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement