当前位置:首页 > 通信资讯 > 正文

.net6性能(net 6.0)

.net6性能(net 6.0)

前言

几乎所有.NET序列化程序的实现基础都是反射。下列代码是Newtonsoft.Json的实现:

  1. protectedvirtualJsonPropertyCreateProperty(MemberInfomember,MemberSerializationmemberSerialization)
  2. {
  3. JsonPropertyproperty=newJsonProperty();
  4. property.PropertyType=ReflectionUtils.GetMemberUnderlyingType(member);
  5. property.DeclaringType=member.DeclaringType;
  6. property.ValueProvider=CreateMemberValueProvider(member);
  7. property.AttributeProvider=newReflectionAttributeProvider(member);
  8. ......
  9. }

反射为某些场景提供了强大的功能,但相对于直接编码,在运行性能上较差,例如Newtonsoft.Json就用缓存进行了优化:

  1. publicvirtualJsonContractResolveContract(Typetype)
  2. {
  3. ValidationUtils.ArgumentNotNull(type,nameof(type));
  4. return_contractCache.Get(type);
  5. }

而在.NET 6中,为System.Text.Json提供了Source Generator,可以在编译时就生成序列化源代码。

Demo

使用方法非常简单。

只需实现一个继承自JsonSerializerContext的类,并声明JsonSerializable,指定序列化的类型:

  1. [JsonSerializable(typeof(WeatherForecast))]
  2. internalpartialclassWeatherForecastContext:JsonSerializerContext
  3. {
  4. }

然后,就可以将自动生成的WeatherForecastContext.Default.WeatherForecast对象作为参数用于序列化:

  1. varstr=JsonSerializer.Serialize(newWeatherForecast
  2. {
  3. TemperatureC=Random.Shared.Next(-20,55),
  4. Summary=Summaries[Random.Shared.Next(Summaries.Length)]
  5. },WeatherForecastContext.Default.WeatherForecast);
  6. varobj=JsonSerializer.Deserialize(str,WeatherForecastContext.Default.WeatherForecast);

单步跟踪,可以看到生成的序列化代码如下,

  1. privatestaticvoidWeatherForecastSerializeHandler(global::System.Text.Json.Utf8JsonWriterwriter,global::WebApplication1.WeatherForecast?value)
  2. {
  3. if(value==null)
  4. {
  5. writer.WriteNullValue();
  6. return;
  7. }
  8. writer.WriteStartObject();
  9. writer.WriteNumber(PropName_TemperatureC,value.TemperatureC);
  10. writer.WriteNumber(PropName_TemperatureF,value.TemperatureF);
  11. writer.WriteString(PropName_Summary,value.Summary);
  12. writer.WriteEndObject();
  13. }

另外,还可以使用JsonSourceGenerationOptionsAttribute对生成的序列化代码进行一定调整,比如属性名大小写:

  1. [JsonSourceGenerationOptions(PropertyNamingPolicy=JsonKnownNamingPolicy.CamelCase)]
  2. [JsonSerializable(typeof(WeatherForecast))]
  3. internalpartialclassWeatherForecastContext:JsonSerializerContext
  4. {
  5. }

结论

在编译时生成源代码可为.NET应用程序带来许多好处,包括提高性能。官方提供的测试结果表明提高了接近40%,有兴趣的朋友可以验证一下:

.net6性能(net 6.0)

原文地址:https://www.toutiao.com/a7050079625048752673/

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。