I have an item with a name, which runs a recursive routine. Part of that execution involves the possible 'running' of other items of the same type.

I need to check that the recusion is not infinite (i.e. an item will never run itself). The nesting is unlimited.

Is there an efficient algorithm to check this? I can build up the list of the item names, and I'd want to exit if a name is already in the list, but the checking could make this prohibitive time-wise.

Is it quicker to build the whole name list and then check for multiple entries? Or check after each addition?

Or is there a better way?

Any suggestions?