Isnt't it better to just reverse the list?

I did the following, and maybe it’s an overkill, but I think it might be better for performance. Or is copying a List not worth the while?

List<DialogueNode> reversedNodes = new List<DialogueNode>(nodes);
      reversedNodes.Reverse();
      foreach (var node in reversedNodes)
      {
        if (node.position.Contains(point)) return node;
      }
      return null;

I would say in this case it’s more of a performance hit than a benefit. The original code cycles through the entire list, but then it’s done. This code makes a copy of each reference on the heap, and then returns the first point, but the Reverse() takes just as long as the original search.

You could optimize the code this way:

for(int i=nodes.Count-1;i>=0;i--)
{
     if(nodes[i].position.Contains(point)) return nodes[i];
}
return null;

This would return the last item under the cursor and short circuit the operation.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms