Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I speed up this method which removes text from a string?

I wrote the following method to remove the namespace in brackets from strings.

I would like to make this as fast as possible.

Is there a way to speed up the following code?

using System;

namespace TestRemoveFast
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] tests = {
            "{http://company.com/Services/Types}ModifiedAt",
            "{http://company.com/Services/Types}CreatedAt"
                             };

            foreach (var test in tests)
            {
                Console.WriteLine(Clean(test));
            }

            Console.ReadLine();
        }

        static string Clean(string line)
        {
            int pos = line.IndexOf('}');
            if (pos > 0)
                return line.Substring(pos + 1, line.Length - pos - 1);
            else
                return line;
        }
    }
}
like image 399
Edward Tanguay Avatar asked Jan 15 '10 13:01

Edward Tanguay


4 Answers

You could try parallelism since it doesn't look like you need a synchronous treatment. A parallel foreach with PLINQ would do the trick.

But if you cannot wait until VS2010 is officially out, you could try Poor Man's Parallel.ForEach Iterator by Emre Aydinceren

like image 53
Dynami Le Savard Avatar answered Nov 15 '22 11:11

Dynami Le Savard


The approach seems to be quiet fast. But from the string you have, I conclude that the name is usually smaller then the {URL}. You can use .LastIndexOf() method. I think it starts from the end of string

like image 29
ata Avatar answered Nov 15 '22 10:11

ata


Let's say you do find an answer here. I think you need to consider what the "solution" is going to look like for the next guy that looks at your code.

I'll take more readable code vs. a couple milliseconds any day.

like image 37
Kris Krause Avatar answered Nov 15 '22 09:11

Kris Krause


Have you tried this with Regex and/or use a stringbuilder instead of a string?

like image 45
Lucas B Avatar answered Nov 15 '22 10:11

Lucas B