LoginSignup
5
6

More than 5 years have passed since last update.

BitConverterは速いってお話は嘘かもしれない

Last updated at Posted at 2015-11-11

BitConverterのパフォーマンスってどうなのかなって思ってたから調べてみた。


    class Program
    {
        const int COUNT = 1000000;
        static void Main(string[] args)
        {
            var basearray = Enumerable.Range(0, 1024).Select(x => (byte)x).ToArray();

            var sw = Stopwatch.StartNew();
            for (var i = 0; i < COUNT; i++)
            {
                var buffer = BitConverter.ToInt64(basearray, 2);
            }
            sw.Stop();

            Console.WriteLine($"BitConverter {sw.ElapsedMilliseconds}ms");

            sw = Stopwatch.StartNew();
            for (var i = 0; i < COUNT; i++)
            {
                var buffer = BtoS<Int64>(basearray, 2);
            }
            sw.Stop();

            Console.WriteLine($"Marshal {sw.ElapsedMilliseconds}ms");

            sw = Stopwatch.StartNew();
            for (var i = 0; i < COUNT; i++)
            {
                var buffer = ToInt64(basearray, 2);
            }
            sw.Stop();

            Console.WriteLine($"unsafe {sw.ElapsedMilliseconds}ms");



            Console.ReadKey();
        }

        private static T BtoS<T>(byte[] bytes, int startIndex) where T : struct
        {
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
            T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject() + startIndex,
                typeof(T));
            handle.Free();
            return stuff;
        }

        unsafe static void PutBytes(byte* dst, byte[] src, int start_index, int count)
        {
            for (int i = 0; i < count; i++)
                dst[i] = src[i + start_index];
        }

        unsafe static Int64 ToInt64(byte[] bytes, int startIndex)
        {
            Int64 ret;

            PutBytes((byte*)&ret, bytes, startIndex, 8);

            return ret;
        }

    }

BitConverter 29ms
Marshal 809ms
unsafe 123ms

BitConverterは速い。
でも書くのメンドクサイ。BitConverter.toInt64(なんてかいてられるかばかやろ~

すいません。コード最適化によって結果が変わります。
http://qiita.com/yu_ka1984/items/fa403894af35a3f3925c

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6