[英]C# - Trying to convert two bytes to ushort resulting to “Cannot implictly convert type 'int' to 'ushort'” error
[英]Memory efficient type to store 8 bytes and 2 ushort values
我需要創建一個行數組。 每行將包含八個 1 字節數字 (0-255) 和兩個 2 字節 ushort 數字 (0-65535)。 我將在 memory 中同時保留數百萬(如果不是數十億)這樣的行。如果我專注於優化 memory 的使用,那么用於構造此類行的最佳類型是什么? 我使用64位操作系統。
我在想簡單的Tuple
,像這樣:
new Tuple<byte[], ushort, ushort>(byteArray, 1, 2);
或結構:
public struct Row
{
public Row(byte[] bytes, ushort val1, ushort val2)
{
Bytes = bytes;
Val1 = val1;
Val2 = val2;
}
public byte[] Bytes { get; set; } = new byte[8];
public ushort Val1 { get; set; }
public ushort Val2 { get; set; }
}
或結構,但沒有字節數組? 像這樣:
public struct Row
{
public byte B1 { get; set; }
public byte B2 { get; set; }
public byte B3 { get; set; }
public byte B4 { get; set; }
public byte B5 { get; set; }
public byte B6 { get; set; }
public byte B7 { get; set; }
public byte B8 { get; set; }
public ushort Val1 { get; set; }
public ushort Val2 { get; set; }
}
我認為數據本身將占用 12 個字節(或者 16 個字節?)。 但我不確定 memory 將用於我不知道的其他內容。 比如數組長度? 我應該使用List
而不是數組嗎?
我應該避免使用數組,並將每個字節存儲在單獨的屬性中嗎?
我應該使用int
而不是ushort
嗎? 如果無論如何一行都需要 16 個字節,那么將int
用於 Val1 和 Val2 不是更好嗎?
需要注意的是,一旦創建了這個包含數十億行的列表,稍后將在算法中更改/更新一些值。 不確定為此選擇完美類型是否重要。
感謝您的建議和幫助!
最后一個選項看起來是最有效的。 如果你想讓它像有一個數組一樣工作,你可以試試這個:
struct A {
private ulong bytes;
// allows you to access the bytes like this is an array
public byte this[int i] {
get => (byte)(bytes >> (i * 8));
set {
bytes &= ~(0b11111111 << (i * 8));
bytes |= value << (i * 8);
}
}
public ushort ushort1;
public ushort ushort2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.