1

Here is my function in which I am using nested loops like:

public string HGSearchNew(HolidayFeedService.PackageHolidays.SearchCriteria objsearchcriteria, dynamic search)
{
        XmlDocument xdoc = new XmlDocument();
        XmlNodeList ndepartures = xdoc.SelectNodes("Destinations/Departure");
        string sFinalDeparture = objsearchcriteria.DepartureAirport.ToUpper();

        for (int i = 0; i < objsearchcriteria.DepartureAirport.Split('|').Length; i++)
        {

            for (int j = 0; j < ndepartures.Count; j++)
            {
                if (objsearchcriteria.DepartureAirport.Split('|')[i].ToUpper() == ndepartures[j]["Name"].InnerText.ToUpper())
                {
                    if (!sFinalDeparture.Contains(objsearchcriteria.DepartureAirport.Split('|')[i].ToUpper()))
                        sFinalDeparture += objsearchcriteria.DepartureAirport.Split('|')[i].ToUpper() + "|";

                    break;
                }
            }
        }
        return sFinalDeparture;
    }    

I want to make this code efficient like instead of using loops,use of Contains or Any functions for comparing. kindly help me out?

11
  • 9
    You should save objsearchcriteria.DepartureAirport.Split('|') inside variable and use that variable instead. otherwise its terrible idea to do split on same string over and over. Commented May 18, 2016 at 13:44
  • 1
    Both. With the ridiculous waste you have there (same with sFinalDeparture as string, instead of creating the string at the end) you just waste memory and speed left and right. Commented May 18, 2016 at 13:46
  • 2
    Few things: in addition to what Akhgary said (which affect - heavily - efficiency) also don't repeat ToUpper() unless necessary and be aware that it's not right way to perform case insensitive string comparison. Recreate a string multiple times is slow, use StringBuilder. Also note that Contains() and Any() with XmlDocument won't affect performance (just slightly degrade them) but for sure not improve. If you want to efficiently use LINQ you should use XDocument (or, with XmlDocument) use XPath whenever possible. Well this is more a question for Code Review than Stack Overflow... Commented May 18, 2016 at 13:47
  • 3
    Where does this false premise that Linq magically improves performance over nested loops come from? Commented May 18, 2016 at 13:51
  • 1
    @user6144226: if i've understood OP's code you can see LINQ's power here. Commented May 18, 2016 at 14:09

1 Answer 1

5

I think you can replace the whole method with this readable and efficient LINQ approach:

public string HGSearchNew(HolidayFeedService.PackageHolidays.SearchCriteria objsearchcriteria)
{
    XmlDocument xdoc = new XmlDocument();
    XmlNodeList ndepartures = xdoc.SelectNodes("Destinations/Departure");
    string[] departureTokens = objsearchcriteria.DepartureAirport.Split('|');

    var matches = ndepartures.Cast<XmlNode>()
        .Select(node => node.Name)
        .Intersect(departureTokens, StringComparer.InvariantCultureIgnoreCase);

    return string.Join("|", matches);
}
Sign up to request clarification or add additional context in comments.

7 Comments

WHooow. Nice. And yes, that is an attempt at intersect... VERY nice.
Actually it may be faster to code everything in upper string - case sensitive comparisons are IIRC faster than case insensitive. Not sure it actually matters, though (as in: unless there are a LOT of checks).
Apart from the fact that you could fail the Turkey Test it's also more efficient to use StringComparison overloads of string-methods (or in this case the Intersect overload that takes a comparer) because you don't give the garbage collector loads of temporary strings(ToUpper) as food.
I do think this is a bit differnt from OP's code since it removes non-matches. But I bet this is what OP wanted anyway.
How have you measured it? With StopWatch or DateTime? If the string is large this approach will definitely be faster. Even if the timespan you've measured is correct, how often have you called this method(warmup time)? However, look at your method compared to this and tell me what is easier to read and maintain ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.