Search code examples
c#stringoptimizationcompiler-optimizationstring-search

Replace string.Split with other constructs - Optimization


Here I am using Split function to get the parts of string.

string[] OrSets = SubLogic.Split('|');
foreach (string OrSet in OrSets)
{
  bool OrSetFinalResult = false;
    if (OrSet.Contains('&'))
    {
        OrSetFinalResult = true;
        if (OrSet.Contains('0'))
        {
            OrSetFinalResult = false;
        }
        //string[] AndSets = OrSet.Split('&');
        //foreach (string AndSet in AndSets)
        //{
        //    if (AndSet == "0")
        //    {
        //        // A single "false" statement makes the entire And statement FALSE
        //        OrSetFinalResult = false;
        //        break;
        //    }
        //}

    }
    else
    {
        if (OrSet == "1")
        {
            OrSetFinalResult = true;
        }
    }

    if (OrSetFinalResult)
    {
        // A single "true" statement makes the entire OR statement TRUE
        FinalResult = true;
        break;
    }
}

How can I replace the Split operation , along with replacement of foreach constructs.


Solution

  • Hypothesis #1

    Depending of the kind of your process, you can parallellize the work :

    var OrSets = SubLogic.Split('|').AsParallel();
    foreach (string OrSet in OrSets)
    {
      ...
      ....
    }
    

    However, this can often leads to problems with multithreaded apps (locking resource, etc.). And you have also to measure the benefits. Switching from one thread to another can be costly. If the job is small, the AsParallel will be slower than a simple sequential loop.

    This is very efficient when you have latency with network resource, or any kind of I/O.

    Hypothesis #2

    Your SubLogic variable is very very very big

    You can, in this case, walk sequentially the file :

    class Program
    {
        static void Main(string[] args)
        {
            var SubLogic = "darere|gfgfgg|gfgfg";
    
            using (var sr = new StringReader(SubLogic))
            {
    
                var str = string.Empty;
                int charValue;
                do
                {
                    charValue = sr.Read();
                    var c = (char)charValue;
                    if (c == '|' || (charValue == -1 && str.Length > 0))
                    {
                        Process(str);
                        str = string.Empty; // Reset the string
                    }
                    else
                    {
                        str += c;
                    }
                } while (charValue >= 0);
    
            }
    
            Console.ReadLine();
        }
    
        private static void Process(string str)
        {
            // Your actual Job
            Console.WriteLine(str);
        }
    

    Also, depending of the length of each chunk between |, you may want to use a StringBuilder and not a simple string concatenation.