通常我需要在非常频繁运行的代码中最小化对象分配。
当然我可以使用像对象池这样的普通技术,但有时我只想要本地包含的东西。
为了尝试实现这一目标,我提出了以下建议:
public static class Reusable<T> where T : new()
{
private static T _Internal;
private static Action<T> _ResetAction;
static Reusable()
{
_Internal = Activator.CreateInstance<T>();
}
public static void SetResetAction(Action<T> resetAction)
{
_ResetAction = resetAction;
}
public static T Get()
{
#if DEBUG
if (_ResetAction == null)
{
throw new InvalidOperationException("You must set the reset action first");
}
#endif
_ResetAction(_Internal);
return _Internal;
}
}
目前,用法是:
// In initialisation function somewhere
Reuseable<List<int>>.SetResetAction((l) => l.Clear());
....
// In loop
var list = Reuseable<List<int>>.Get();
// Do stuff with list
我想改进的是,整个东西不包含在一个地方(.SetResetAction
它与实际使用的地方是分开的)。
我想让代码如下所示:
// In loop
var list = Reuseable<List<int>>.Get((l) => l.Clear());
// Do stuff with list
这个问题是我得到一个对象分配(它创建一个Action<T>
)每个循环。
是否有可能在没有任何对象分配的情况下获得我想要的用法?
显然我可以创建一个ReuseableList<T>
内置的,Action
但我想允许其他情况下操作可能会有所不同。