简体   繁体   中英

Recursive function with big dictionary caused stack overflow problem

I have this recursive function that generates a tree, when the dictionary is smaller, it works fine, but when the dictionary gets bigger, it throws me a stack overflow exception. I know that I shouldn't be increasing the stack to solve the problem. Is there any idea to optimize this recursive function?

public async static Task<SchemaNodeForGetDto> schemaDecompositionGenerator ( SchemaNodeForGetDto startNode, Dictionary<string, OntologyObjectAttrDictionaryDto> objectsLibrary, Dictionary<string, OntologyObjectPartsDto> objectDecompo, ILogger _logger )
    {
        //get child of the start node
        IEnumerable<OntologyObjectPartDto> decompoParts = objectDecompo[startNode.uri].parts;
        IEnumerable<SchemaNodeForGetDto> children = await Task.WhenAll(decompoParts.Select(async x => {
            SchemaNodeForGetDto node = new SchemaNodeForGetDto();
            node.uri = x.partIri;
            node.name = objectsLibrary.ContainsKey(x.partIri) ? objectsLibrary[x.partIri].en : "";
            node.constraint = x.constraint;
            node.attributes = objectsLibrary.ContainsKey(x.partIri) ? objectsLibrary[x.partIri].attributes : Enumerable.Empty<string>();

            //recursive the tree generation
            if (objectDecompo.ContainsKey(node.uri)) {
                await schemaDecompositionGenerator(node, objectsLibrary, objectDecompo, _logger);
            }

            // return the child node
            return node;
        }));

        startNode.children = children;

        return startNode;

    }

i don't know how to use iteration in this case to construct the tree

Recursive functions can be transformed to iterative functions by maintaining your own stack (or queue) explicitly.

Alternatively, if you want a quick solution, you can add await Task.Yield(); at the beginning of your method.

So I end up solving this stack overflow issue by reducing the data in each recursive call, and it worked well, Thought sharing the solution. might be useful for others who search for a quick solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM