byte + byte = int… why?

前端 未结 16 2404
长情又很酷
长情又很酷 2020-11-22 04:33

Looking at this C# code:

byte x = 1;
byte y = 2;
byte z = x + y; // ERROR: Cannot implicitly convert type \'int\' to \'byte\'

The result of

16条回答
  •  我寻月下人不归
    2020-11-22 05:12

    I've test performance between byte and int.
    With int values :

    class Program
    {
        private int a,b,c,d,e,f;
    
        public Program()
        {
            a = 1;
            b = 2;
            c = (a + b);
            d = (a - b);
            e = (b / a);
            f = (c * b);
        }
    
        static void Main(string[] args)
        {
            int max = 10000000;
            DateTime start = DateTime.Now;
            Program[] tab = new Program[max];
    
            for (int i = 0; i < max; i++)
            {
                tab[i] = new Program();
            }
            DateTime stop = DateTime.Now;
    
            Debug.WriteLine(stop.Subtract(start).TotalSeconds);
        }
    }
    

    With byte values :

    class Program
    {
        private byte a,b,c,d,e,f;
    
        public Program()
        {
            a = 1;
            b = 2;
            c = (byte)(a + b);
            d = (byte)(a - b);
            e = (byte)(b / a);
            f = (byte)(c * b);
        }
    
        static void Main(string[] args)
        {
            int max = 10000000;
            DateTime start = DateTime.Now;
            Program[] tab = new Program[max];
    
            for (int i = 0; i < max; i++)
            {
                tab[i] = new Program();
            }
            DateTime stop = DateTime.Now;
    
            Debug.WriteLine(stop.Subtract(start).TotalSeconds);
        }
    }
    

    Here the result:
    byte : 3.57s 157mo, 3.71s 171mo, 3.74s 168mo with CPU ~= 30%
    int : 4.05s 298mo, 3.92s 278mo, 4.28 294mo with CPU ~= 27%
    Conclusion :
    byte use more the CPU but it cost les memory and it's faster (maybe because there are less byte to alloc)

提交回复
热议问题