performance of byte vs. int in .NET

后端 未结 5 687
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 18:49

In pre-.NET world I always assumed that int is faster than byte since this is how processor works.

Now it\'s matter habit of using int even when bytes could work, fo

5条回答
  •  梦谈多话
    2021-01-17 19:27

    Are you talking about storage space or operations on a byte? If it's storage space, yes it takes up less space than an int (1 byte vs 4 bytes).

    In terms of arithmetic operations on a byte, I don't have raw numbers and really only a profiler can give them to you. However you should consider that arithmetic operations are not done on raw byte instances. Instead they are promoted to int's and then the operation is done on an int. This is why you have to explicitly cast operations like the following

    byte b1 = 4;
    byte b2 = 6;
    byte b3 = b1 + b2;  // Does not compile because the type is int
    

    So in the general case I think it's safe to say that arithmetic operations on an int are faster than that of a byte. Simply because in the byte case you pay the (probably very small) cost of type promotion.

提交回复
热议问题