簡體   English   中英

將HttpResponseMessage內容設置為字符串和JSON文件之間是否有性能差異?

[英]Is there any performance difference between setting HttpResponseMessage content as string and as JSON file?

我正在嘗試使用以下序列化大對象。 但是有時會拋出內存不足異常。

方法1:

            var settings = new JsonSerializerSettings { ContractResolver = BaseFirstContractResolver.Instance };
           string jsonString = JsonConvert.SerializeObject(listObj, Newtonsoft.Json.Formatting.Indented, settings);

所以我決定將對象序列化為文件,如下所示,

方法2:

            string path = System.Web.Configuration.WebConfigurationManager.AppSettings["jsonPath"].ToString();
            using (StreamWriter file = File.CreateText(path))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, listObj);
            }
        }

我也從HttpResponseMessage從文件返回json數據,

string path = System.Web.Configuration.WebConfigurationManager.AppSettings["jsonPath"].ToString();
                var stream = new System.IO.FileStream(path, System.IO.FileMode.Open);
                var response = this.Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                return response;

我在方法1中比在方法2中更快地獲取數據。這兩種方法之間是否存在性能差異?

第一種方法是使用內存,第二種方法是寫入磁盤,然后再次從磁盤讀取。 第一種方法將始終更快,但是會占用更多內存。 性能上的差異將在很大程度上取決於內存和磁盤的IO速度。 我個人不惜一切代價避免使用方法2。 如果對象是某種類型的集合,我將在方法1上實現分頁。 如果我被迫在一個請求中發送整個集合,則對集合的大塊使用yield返回。 這將創建分塊的傳輸編碼流。 如果該對象確實只是一個巨大的單個對象,則將需要某種類型的流解串器以再次對分塊的傳輸編碼流進行處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM