모름

백준 알고리즘을 풀다가 더 빠르게 문자열을 입력받는 방법이 무엇일까 찾는 와중에 String.Split과 StringReader type 중 무엇이 더 효율적인지 비교하는 코드를 봤다.

 

https://www.dotnetperls.com/stringreader

 

C# StringReader Class (Get Parts of Strings) - Dot Net Perls

Internals. The internal representation of the StringReader is a class with a member field string, an integer position, and an integer length. All the logic on the StringReader is based on the values of these three fields. Summary. StringReader provides met

www.dotnetperls.com

자세한건 위 사이트에서 천천히 읽어보는게 좋을 것 같고...

코드

using System;
using System.Diagnostics;
using System.IO;

class Program
{
    static int Method1(string data)
    {
        int count = 0;
        StringReader reader = new StringReader(data);
        {
            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                {
                    break;
                }
                count += line.Length;
            }
        }
        return count;
    }

    static int Method2(string data)
    {
        int count = 0;
        string[] lines = data.Split(new char[] { '\n' });
        foreach (string line in lines)
        {
            count += line.Length;
        }
        return count;
    }

    static void Main()
    {
        string data = "Dot\nNet\nPerls\nIs a website\nDo you like it?";
        Console.WriteLine(Method1(data));
        Console.WriteLine(Method2(data));
        const int max = 1000000;

        var s1 = Stopwatch.StartNew();
        for (int i = 0; i < max; i++)
        {
            Method1(data);
        }
        s1.Stop();

        var s2 = Stopwatch.StartNew();
        for (int i = 0; i < max; i++)
        {
            Method2(data);
        }
        s2.Stop();

        Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / max).ToString("0.00 ns"));
        Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / max).ToString("0.00 ns"));
        Console.Read();
    }
}

실행화면

보면 알겠지만 StringReader로 읽은 문자열이 Split보다 빠르다. 여기까지. 나중에 써먹어볼 문제가 있으면 써먹어봐야겠다.