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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With