這是JsonResult
類型的內部代碼。
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
JavaScriptSerializer scriptSerializer = new JavaScriptSerializer();
if (this.MaxJsonLength.HasValue)
scriptSerializer.MaxJsonLength = this.MaxJsonLength.Value;
if (this.RecursionLimit.HasValue)
scriptSerializer.RecursionLimit = this.RecursionLimit.Value;
response.Write(scriptSerializer.Serialize(this.Data));
}
從視內部碼點,所述JavaScriptSerializer
是用於序列化傳遞到JsonResult
對象的類型。您可以檢查這是否是您的代碼採取緩慢流程的步驟。
試着讓你的控制器是這樣的:
public JsonResult Read(....)
{
var all = _userManager.GetStuff();
var watch = Stopwatch.StartNew();
var scriptSerializer = new JavaScriptSerializer();
var json = scriptSerializer.Serialize(all);
Trace.WriteLine("READ" + watch.ElapsedMilliseconds);
watch.Stop();
return json; //Takes 40 milliseconds to get here
}
如果問題仍然存在,你可以實現一個替代方案,你可以使用JSON.Net
庫,它可以提供better results實現自己的JsonResult。對於樣品,添加命名空間:
using Newtonsoft.Json;
控制器:
public JsonResult Read(....)
{
var all = _userManager.GetStuff();
var watch = Stopwatch.StartNew();
var json = JsonConvert.SerializeObject(all);
Trace.WriteLine("READ" + watch.ElapsedMilliseconds);
watch.Stop();
return Content(json, "application/json"); //Takes 40 milliseconds to get here
}
最後,你可以比較的性能。另一種可能的方法是使用另一種可以加快序列化的格式,例如xml或binary。
總共有多少項,東東對象是簡單對象還是複雜? –