Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect and avoid infinite loops? [closed]

I want to make sure that my web application is performance wise and will not make any performance problems. When I searched, I found that one of the most common problems related to the performance issue is the "infinite loops" problem.

I want to ask:

Where should I begin to check that my code never causes infinite loops?

Are there any articles, advices, instructions, examples? I will be grateful.

ex:

May this code cause an infinite loop?

public static IEnumerable<SubjectNode> ReadSubjectNodes(string filePath)
{
    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    using (XmlReader xrdr = new XmlTextReader(fs))
        while (xrdr.Read())
            if (xrdr.NodeType == XmlNodeType.Element && xrdr.LocalName == "subject")
                yield return new SubjectNode(xrdr.GetAttribute("id"), xrdr.GetAttribute("name"), xrdr.GetAttribute("short"));
}

Thanks in advance

like image 985
Anyname Donotcare Avatar asked Jan 16 '12 12:01

Anyname Donotcare


1 Answers

Well, AFAIK that code won't cause an infinite loop - it is not recursive, and an XmlReader from the file-system will eventually run out of data. It might be long running, though. In some cases, adding a sanity check may help - this could be a counter, or a check against the time. For example:

public static IEnumerable<SubjectNode> ReadSubjectNodes(string filePath)
{
    int safetyCheck = 10000;
    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    using (XmlReader xrdr = new XmlTextReader(fs))
        while (xrdr.Read()) {
            if(--safetyCheck == 0) throw new SomeTypeOfException();
            ... more code
        }
    ... more code
}
like image 175
Marc Gravell Avatar answered Sep 21 '22 06:09

Marc Gravell