看板 C_Sharp 關於我們 聯絡資訊
每當一些Stream或XML交換時,我特別喜歡用MemoryStream 若有需要轉成byte[]陣列,就會用GetBuffer()直接操作這底下的陣列 也可以使用ToArray()來複製新的陣列。 直覺下使用GetBuffer()的陣列會比較不需耗效能copy 但就是怕其存活期會在stream.Close()後消失 我作了一個實驗: System.IO.MemoryStream ms = new System.IO.MemoryStream(3); // Capacity=3 byte[] bb1 = {1, 2, 3, 4}; // Make it over ms capacity. ms.Write(bb1, 0, bb1.Length); // Capacity=256 by system allocated. byte[] bb2 = ms.ToArray(); // bb2.Length=4, copy items. byte[] bb3 = ms.GetBuffer(); // bb3.Length=256, as capacity but not copy items (faster). ms.Close(); GC.Collect(0); GC.Collect(1); GC.Collect(2); byte[] bb4 = ms.ToArray(); // Still work. byte[] bb5 = ms.GetBuffer(); // Still work. ms.Dispose(); GC.Collect(0); GC.Collect(1); GC.Collect(2); byte[] bb6 = ms.ToArray(); // Still work, what the hell dispose? byte[] bb7 = ms.GetBuffer(); // Still work, what the hell dispose? 看來都能存活~ 但真的存活期是這樣嗎? 若要輸出byte[]時,您覺得用那一個函式比較好呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ※ 編輯: tomex 來自: 111.250.105.59 (10/27 13:26)
tomex:後來我使用ToArray()保險些,長度不用小心,資料量<1K 10/27 13:36
justinlcs:MemoryStream並沒有包含任何unmanaged資源。 10/27 20:34
justinlcs:換言之並沒有東西需要特別Dispose或Close 10/27 20:35
justinlcs:GC會自動處裡MemoryStream的生命週期,在不需要時清除 10/27 20:38
justinlcs:只是剛好繼承了Stream,有這些方法而已 10/27 20:39
tomex:thx 10/28 02:10