It'sNotALie.
It'sNotALie.

Reputation: 22804

What's the most efficient way to access the value of a match?

There are many ways to access a Match's value in C#:

Match mtch = //whatever
//you could do
mtch.Value
//or 
mtch.ToString()
//or
mtch.Groups[0].Value
//or 
mtch.Groups[0].ToString()

My question is: what is the best way to access it?

(I know this is micro-optimization, I'm just wondering)

Upvotes: 1

Views: 88

Answers (3)

WhileTrueSleep
WhileTrueSleep

Reputation: 1534

  1. Write a test
  2. Read result
  3. Think about result

If you don't want to write tests look at the Microsoft Intermediate Language (MSIL) and think about what will take more time


i also tested it with the result

            // VS 2012 Ultimate
            // 
            Regex r = new Regex(".def.");
            Match mtch = r.Match("abcdefghijklmnopqrstuvwxyz", 0);
            string a, b, c, d;
            for (int i = 0; i < int.MaxValue; i++)
            {
               a = mtch.Value;                  // 1.4%
               b = mtch.ToString();             // 33.2%
               c = mtch.Groups[0].Value;        // 15.3%
               d = mtch.Groups[0].ToString();   // 44.1%
            }

Upvotes: 0

Chris
Chris

Reputation: 2806

I wrote a quick test and ended up with the following result...

    [TestMethod]
    public void GenericTest()
    {
        Regex r = new Regex(".def.");
        Match mtch = r.Match("abcdefghijklmnopqrstuvwxyz", 0);
        for (int i = 0; i < 1000000; i++)
        {
            string a = mtch.Value;                  // 15.4%
            string b = mtch.ToString();             // 19.2%
            string c = mtch.Groups[0].Value;        // 23.1%
            string d = mtch.Groups[0].ToString();   // 38.5%
        }
    }

Upvotes: 2

COLD TOLD
COLD TOLD

Reputation: 13599

If you are talking about effiecency based on the samples you provide I would guess that the most efficient would be the first one since when you use ToSting() it adds an extra conversion functionality to your variable which would take an extra time,

Upvotes: 0

Related Questions