суббота, 1 марта 2008 г.

Compare string performance using C#,C++(STL,boost) and C - part 1, C#

Compare string performance using C#,C++(STL,boost) and C - part 2, C\C++
Compare string performance using C#,C++(STL,boost) and C - part 3, results

This comparation was inspired by STL vector performance

Task -
you have array of strings "word1-word2", "word3-word4", "word5-word6", you need to transform it to string "word1:word2:word3:word4:word5:word6"


I was doing this on Windows so I use QueryPerformanceCounter to test performance to keep performance testing the same with C# and C++.

Main C# piece of code:

string r = ":".join(array1.SelectMany(x => x.Split('-')));


Whole C# code:

using System;

using System.Linq;

using System.Collections.Generic;

using System.Runtime.InteropServices;

 

namespace MainProgramm

{

    static class string_extentions

    {

        public static string join(this string a, IEnumerable<string> elems)

        {

            string result = "";

            foreach (string elem in elems) {

                if (result.Length != 0)

                    result += a;

                result += elem;

            }

            return result;

        }

    }

    internal class HiPerfTimer

    {

        [DllImport("Kernel32.dll")]

        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

 

        [DllImport("Kernel32.dll")]

        private static extern bool QueryPerformanceFrequency(out long lpFrequency);

 

        private long startTime, stopTime;

        private long freq;

        public HiPerfTimer(){QueryPerformanceFrequency(out freq);}

        public void    start   (){QueryPerformanceCounter(out startTime);}

        public void    stop    (){QueryPerformanceCounter(out stopTime);}

        public double   duration{

            get{return (double)(stopTime - startTime) / (double)freq;}

        }

    }

 

    class Program

    {

        static void test_functional()

        {

            string[] array1 = { "word1-word2", "word3-word4", "word5-word6", "word7-word8", "word9-word0" };

            HiPerfTimer pt = new HiPerfTimer();

            pt.start();

            for (int i = 0; i < 10000; ++i) {

                string r = ":".join(array1.SelectMany(x => x.Split('-')));

            }

            pt.stop();

 

            Console.WriteLine("C# functional - {0} sec\n", pt.duration); // print the duration of the timed code

        }

        static void Main(string[] args){

            test_string_builder();

            test_functional();

        }

    }

}

Комментариев нет: