当前位置:网站首页>0x02 - create and cache object visitors
0x02 - create and cache object visitors
2020-12-14 23:27:43 【Newbe36524】
Create and cache Object Visitor.
It's all about being more efficient
Previous articles , We use a simple example to show how to use Object Visitor to OrderInfo
All properties of the link and output .
Although the effect has been achieved , But in order to simplify the space, there are still some poor performance practices , In this section, we will introduce the use of Newbe.ObjectVisitor A truly complete posture .
cache Object Visitor
The core code of the previous section is as follows :
var sb2 = new StringBuilder();
var visitor = order.V()
.ForEach((name, value) => sb2.AppendFormat("{0}: {1}{2}", name, value, Environment.NewLine));
visitor.Run();
Console.WriteLine(sb2.ToString()); |
In this code , We directly created a object visitor , And then use it directly later , And then the method just ends .
For disposable use object visitor Come on , There's no problem with that . But if the code is on a common hotspot path , This repeats the creation of object visitor There is no doubt that it is a waste . therefore , We can think about caching object visitor In static fields .
therefore , We've got the following code :
using System;
using System.Text;
using Newbe.ObjectVisitor;
namespace yueluo_dalao_yes
{
class Program
{
private static readonly StringBuilder _sb = new StringBuilder();
private static readonly ICachedObjectVisitor<OrderInfo> _visitor = default(OrderInfo).V()
.ForEach((name, value) => _sb.AppendFormat("{0}: {1}{2}", name, value, Environment.NewLine))
.Cache();
static void Main(string[] args)
{
var order = new OrderInfo
{
OrderId = 1,
Buyer = "yueluo",
TotalPrice = 62359.1478M
};
_visitor.Run(order);
Console.WriteLine(_sb.ToString());
}
}
public class OrderInfo
{
public int OrderId { get; set; }
public string Buyer { get; set; }
public decimal TotalPrice { get; set; }
}
} |
here , We made these changes :
- take object visitor Changed to a static field , And use field initialization to assign values .
- initialization object visitor when , Because of this time
OrderInfo
The object has not yet been determined , Therefore usedefault(OrderInfo)
To express object visitor The type of target that needs to be accessed . - We are
ForEach
Behind , CalledCache
Method to create a cached good object visitor. The implementation details can be explained here :Cache
It's actually compiling an expression into a delegate , In this way, the delegate can be used repeatedly later , To achieve the best performance . - Because it is initialized in a static field , therefore
ForEach
MediumStringBuilder
The object must also be a static field , So we also define it in_sb
Field . - Through the above transformation , We can directly use the cached
_visitor
To create a formatted string .
You also need to Extend Object
Last section , We're going through a simple transformation , take object visitor It's cached , Avoid creating many times object visitor The cost of .
however , Left behind a very serious problem :ForEach
Static fields are used directly _sb
String splicing , This can lead to , Multiple calls _visitor.Run(order)
Will continue to splice on the original basis . This is obviously unreasonable .
In response to the object visitor During the running process, except for the accessed object (order
) In addition to processing , You need an extra object (StringBuilder
), We added a new one called Extend Object Characteristics of .
Next , Let's transform the example from the previous section :
using System;
using System.Text;
using Newbe.ObjectVisitor;
namespace yueluo_dalao_yes
{
class Program
{
private static readonly ICachedObjectVisitor<OrderInfo, StringBuilder> _visitor = default(OrderInfo).V()
.WithExtendObject<OrderInfo, StringBuilder>()
.ForEach((name, value, sb) => sb.AppendFormat("{0}: {1}{2}", name, value, Environment.NewLine))
.Cache();
static void Main(string[] args)
{
var order = new OrderInfo
{
OrderId = 1,
Buyer = "yueluo",
TotalPrice = 62359.1478M
};
var sb1 = new StringBuilder();
_visitor.Run(order, sb1);
Console.WriteLine(sb1.ToString());
var sb2 = new StringBuilder();
_visitor.Run(order, sb2);
Console.WriteLine(sb2.ToString());
}
}
public class OrderInfo
{
public int OrderId { get; set; }
public string Buyer { get; set; }
public decimal TotalPrice { get; set; }
}
} |
here , We made these changes :
- adopt
WithExtendObject
Extension method , Designated our object visitor You need to pass in aStringBuilder
Type as Extend Object. - Revised
ForEach
To receive incoming from the outsideStringBuilder
, And call its splicing method . - Revised
_visitor.Run
Call method of . because , It's not just about passingorder
, There is also a need to pass onStringBuilder
As Extend Object. - Run this sample , You'll find that the same information is output twice , This is exactly what we want .
adopt Extend Object, We can do that ForEach
In order to implement some logic .
We can also optimize
We can use generic static classes to cache our object visitor, In this way, we can implement all types of attribute splicing function :
using System;
using System.Text;
using Newbe.ObjectVisitor;
namespace yueluo_dalao_yes
{
class Program
{
static void Main(string[] args)
{
var order = new OrderInfo
{
OrderId = 1,
Buyer = "yueluo",
TotalPrice = 62359.1478M
};
Console.WriteLine(order.FormatToString());
}
}
public static class FormatToStringExtensions
{
public static string FormatToString<T>(this T obj)
{
var sb = new StringBuilder();
FormatStringVisitor<T>.Instance.Run(obj, sb);
var re = sb.ToString();
return re;
}
private static class FormatStringVisitor<T>
{
internal static readonly ICachedObjectVisitor<T, StringBuilder> Instance = CreateFormatToStringVisitor();
private static ICachedObjectVisitor<T, StringBuilder> CreateFormatToStringVisitor()
{
var re = default(T)!
.V()
.WithExtendObject<T, StringBuilder>()
.ForEach((name, value, s) => s.AppendFormat("{0}:{1}{2}", name, value,
Environment.NewLine))
.Cache();
return re;
}
}
}
public class OrderInfo
{
public int OrderId { get; set; }
public string Buyer { get; set; }
public decimal TotalPrice { get; set; }
}
} |
here , We made these changes :
- We added a
FormatToStringExtensions
Static class to add an extension methodFormatToString
, So all types of objects haveFormatToString
This method . - Added one
FormatStringVisitor<T>
Generic static classes , Use it to create and save a object visitor Instance toInstance
attribute , So each type T There are independent object visitor. - Call... Where formatting is needed
FormatToString
Method , You can complete the same logic you need to implement earlier .
This is the final complete plan . actually ,FormatToString
The method is already in Newbe.ObjectVisitor There is a built-in , The implementation method is as described above :
Click here to see FormatToStringExtensions Source code
Summary of this article
Through this article , We've used it through a series of optimizations object visitor The best paradigm for .
The best paradigm has been able to be applied in most scenarios .
Of course , There are more advanced uses waiting for you to discover .
You can click here to see whether to use caching or not object visitor The benchmark of
Release notes
- Newbe.ObjectVisitor 0.4.4 Release , The Model Validator goes online
- Newbe.ObjectVisitor 0.3.7 Release , Automatic generation FluentAPI
- Newbe.ObjectVisitor 0.2.10 Release , More colorful
- Newbe.ObjectVisitor 0.1.4 Release , The initial release
Use samples
- Newbe.ObjectVisitor Examples 1
- 0x01 - My first one Object Visitor
- 0x02 - Create and cache Object Visitor
- 0x03-ForEach Overall view
- 0x04 - Filter properties
- 0x05 - Comprehensive examples , export CSV
Development documents may change with version , To view the latest development documents, you need to step forward http://cn.ov.newbe.pro
Share with others
- Looking for better performance dynamics Getter and Setter programme
- Looking for a smaller immutable dictionary with better performance
- I'm drawing ,FluentAPI She made it by herself
GitHub Project address :https://github.com/newbe36524/Newbe.ObjectVisitor
Gitee Project address :https://gitee.com/yks/Newbe.ObjectVisitor
- The author of this article : newbe36524
- Link to this article : https://www.newbe.pro/Newbe.ObjectVisitor/002-create-and-cache-your-object-visitor/
- Copyright notice : All articles in this blog except special statement , All adopt BY-NC-SA license agreement . Reprint please indicate the source !
版权声明
本文为[Newbe36524]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/202012142327317861.html
边栏推荐
- OPTIMIZER_TRACE详解
- 使用Consul实现服务发现:instance-id自定义
- OPTIMIZER_ Trace details
- Using consult to realize service discovery: instance ID customization
- Summary of common string algorithms
- Summary of common algorithms of linked list
- Linked blocking Queue Analysis of blocking queue
- 构建者模式(Builder pattern)
- Builder pattern
- Newbe.ObjectVisitor 样例 1
猜你喜欢
-
Newbe.ObjectVisitor Example 1
-
Farewell to runaway
-
LeetCode Algorithm 0060 - Permutation Sequence (Medium)
-
编程基础 - 栈的应用 - 混洗(Stack Shuffling)
-
LeetCode Algorithm 0060 - Permutation Sequence (Medium)
-
Fundamentals of programming stack shuffling
-
【色卡】常用色谱简析,中国传统颜色卡,代码附RBG,HC
-
[color card] brief analysis of commonly used chromatograms, Chinese traditional color cards, code with RBG, HC
-
MongoDB 副本集之入门篇
-
Introduction to mongodb replica set
随机推荐
- My name is mongodb, don't understand me. After reading my story, you will get started!
- roboguide破解安装教程
- Roboguide cracking installation tutorial
- The transformation of town street intelligent street lamp under the industrial intelligent gateway
- Remote smoke monitoring of environmental protection data acquisition instrument under Internet of things
- JS实现鼠标移入DIV随机变换颜色
- Flutter 页面中的异常处理ErrorWidget
- Exception handling errorwidget in fluent page
- Bolt's practice of route management of flutter (page decoupling, process control, function expansion, etc.)
- C语言系统化精讲 重塑你的编程思想 打造坚实的开发基础
- Skywalking系列博客6-手把手教你编写Skywalking插件
- Skywalking series blog 7 - dynamic configuration
- Skywalking series blog 6 - help you write skywalking plug-in
- 博客主机_自动申请续期免费证书
- Blog host_ Automatic renewal of free certificate
- 0x05 - 综合示例,导出 CSV
- 0x05 - synthesis example, export to CSV
- flutter圆形或线型进度条
- flutter给滚动内容添加粘性header组件
- Fluent round or linear progress bar
- Fluent adds sticky header components to scrolling content
- Typora uses latex to insert mathematical formulas
- 配电自动化终端dtu
- How to write a thesis opening report
- 基于C的PHP快速IP解析扩展,IP检测
- Based on C PHP fast IP resolution extension, IP detection
- 点击平滑滚动效果
- Click smooth scrolling effect
- HighGo Database触发器使用案例(APP)
- Use case of highgo database trigger (APP)
- ES6之Map对象
- Flutter 最常出现的错误
- Flutter's most common mistakes
- 捕获 flutter app的崩溃日志并上报
- Capture and report the crash log of the flutter app
- SQL Server递归查询在Highgo DB中实现 (APP)
- Implementation of SQL Server recursive query in highgo dB (APP)
- 关于browserslist配置项
- About browserlist configuration items
- FTK1000使用视频一招搞定多模光损耗