这纯粹是为了实验目的和/或学习练习.本质上,我想看看是否可以通过创建一个只初始化一次的类来减少使用Task.Run(()=>Func<>())
时创建的闭包的占用空间.第一,目标是避免每次运行时都创建一个"新"实例,这可能比我想象的闭包本身效率低(但我知道这仅仅是猜测).因此,创建一个基本类来实现这一点是相当简单的,因为您可以在堆栈中找到示例.
然而,我遇到的问题是,在我看来,如果我想使用另一个类的成员和函数,必须封装它们,或者将它们注入到我们将达到Run
的类中,尽管它可能比原始类本身的数据更少,但可能不会有太大的改进.
所以说,我有一些大致的 idea :
internal async Task<PathObject> PopulatePathObjectAsync(Vector3Int origin, Vector3Int destination, PathObject path)
{
return await Task.Factory.StartNew(() => PopulatePathObject(origin, destination, path));
}
/// Not sure if we want to make this a task or not because we may just parallelize and await the outer task.
/// We'll have to decide when we get down to finalization of the architecture and how it's used.
internal PathObject PopulatePathObject(Vector3Int origin, Vector3Int destination, PathObject path)
{
Debug.Log($"Pathfinding Search On Thread: ({System.Threading.Thread.CurrentThread.ManagedThreadId})");
if (!TryVerifyPath(origin, destination, ref path, out PathingNode currentNode))
return path;
var openNodes = m_OpenNodeHeap;
m_ClosedNodes.Clear();
openNodes.ClearAndReset();
openNodes.AddNode(currentNode);
for (int i = CollectionBufferSize; openNodes.Count > 0 && i >= 0; i--)
{
currentNode = ProcessNextOpenNode(openNodes);
if (NodePositionMatchesVector(currentNode, destination))
{
return path.PopulatePathBufferFromOriginToDestination(currentNode, origin, PathState.CompletePath);
}
ProcessNeighboringNodes(currentNode, destination);
}
return path.PopulatePathBufferFromOriginToDestination(currentNode, origin, PathState.IncompletePath);
}
为了省go lambda、闭包和委托的创建(或强制转换?),我需要一个真正封装PopulatePathObject
函数的类,要么直接复制必要的成员,要么将它们作为参数传递.所有这一切似乎都可能带来任何好处.所以有没有办法让我有这样的...
private class PopulatePathObjectTask
{
private readonly Vector2Int m_Origin;
private readonly Vector3Int m_Destination;
private readonly PathObject m_Path;
public PopulatePathObjectTask(Vector2Int origin, Vector3Int destination, PathObject path)
{
m_Origin = origin;
m_Destination = destination;
m_Path = path;
}
public PathObject PopulatePathObject(Vector3Int origin, Vector3Int destination, PathObject path)
{
///Obviously here, without access to the actual AStar class responsible for the search,
///I don't have access to the functions or the class members such as the heap or the hashset
///that represents the closed nodes as well as the calculated buffer size based on the space-state
///dimensions. With that, I'd just be recreating the class and not avoiding much, if any,
///of the overhead created by the closure capturing the class in the first place.
}
}
我可以用它来访问已经存在的功能?我一直在考虑为打开/关闭 node 集合创建静态成员并使用依赖项注入,但我认为,或者更确切地说,希望有人可能对此有更深入的了解,除了它毫无意义,甚至possible的开销减少或性能yield 将是如此微不足道,以至于它毫无意义.当然,你可能是对的,但我这样做只是一种练习,我希望能够真正衡量其中的差异.我甚至可能不会使用它,甚至可能会抛弃AStar而转而使用JPS,但在继续之前我想知道.我不能完全确定,但似乎关闭必须及时捕获整个AStar对象,人们希望通过引用.