我已经实现了一个位图适配器来扩展位图功能,如下所示:
unit UBitmapHelper;
IBmpUtils = interface
procedure SomeNewRoutine;
end;
TBitmapUtilsAdapter = class (TInterfacedObject, IBmpUtils)
public
constructor Create (ABitmap: TBitmap);
//IBmpUtils
procedure SomeNewRoutine;
end;
TBitmapHelper = class helper for TBitmap
function Utils: IBmpUtils; //method factory pattern
end;
function TBitmapHelper.Utils: IBmpUtils;
begin
Result := TBitmapUtilsAdapter.Create(Self);
end;因此,我现在可以如下所示地使用这个适配器:
uses UBitmapHelper;
procedure Test;
var
MyBitmap: TBitmap;
i: Integer;
begin
MyBitmap := TBitmap.Create;
MyBitmap.SetSize(50, 50);
for i := 1 to 100 do
MyBitmap.Utils.SomeNewRoutine;
FreeAndNil(MyBitmap);
end;我不需要释放Utils作为我从TInterfacedObject继承的适配器,所以它将自动释放时,外出测试过程范围,很好!但也许有一点性能问题。
编译器是否为每次迭代创建了一个新的Utils实例,或者在这种情况下,它足够聪明地重用相同的Utils实例,而它位于相同的作用域?
显然,我可以在for-循环之前得到实例,然后在内部使用它,但是我正在试图找出如何在不影响性能的情况下在任何地方使用表示法MyBitmap.Utils.SomeNewRoutine。是做这件事的方法吗?
注:我使用的是Delphi 10.3
编辑
更清楚的是:
是否有任何方法可以做到这一点,而不像上面描述的那样造成性能损失(即在循环中使用表示法)?
发布于 2020-06-12 16:27:15
在注释中,主要目标是能够为每个bm.Utils.SomeProcA值bm编写类似TBitmap、bm.Utils.SomeProcB之类的东西,并且尽可能少的开销(性能损失)。我的第一个想法是尝试
type
TBitmapUtils = record
private
FBitmap: TBitmap;
public
procedure MyProc1;
procedure MyProc2;
end;
TBitmapHelper = class helper for TBitmap
function Utils: TBitmapUtils; inline;
end;哪里
{ TBitmapUtils }
procedure TBitmapUtils.MyProc1;
begin
ShowMessageFmt('The width of the bitmap is %d.', [FBitmap.Width]);
end;
procedure TBitmapUtils.MyProc2;
begin
ShowMessageFmt('The height of the bitmap is %d.', [FBitmap.Height]);
end;
{ TBitmapHelper }
function TBitmapHelper.Utils: TBitmapUtils;
begin
Result.FBitmap := Self;
end;https://stackoverflow.com/questions/62347295
复制相似问题