我突然感觉自己跟个门外汉似的,var是弱类型,那么直接类生成对象的方式叫什么竟然不知道了。那就不管了,以后再了解,这几天看关于性能的东西,发现很多人在实例化的时候都是使用弱类型的,然后我就想测试一下弱类型的实例化与普通方式的实例化在性能上有什么不同,于是借助这CodeTimer写了下面的小段来进行测试。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
Action<TextBox,
string
> UpdateUI =
new
Action<TextBox,
string
>((ui, msg) =>
{
ui.Dispatcher.Invoke(
new
Action(() =>
{
ui.Text = msg;
}));
});
int
count = 1000;
StringBuilder result =
new
StringBuilder();
CodeTimer.Initialize();
CodeTimer.Time(
"通过类直接实例化"
, count, () =>
{
Button btn =
new
Button();
btn.Content =
"OK"
;
}, (msg) => { result.AppendLine(msg); Console.WriteLine(msg); });
CodeTimer.Time(
"弱类型实例化"
, count, () =>
{
var btn =
new
Button();
btn.Content =
"OK"
;
}, (msg) => { result.AppendLine(msg); Console.WriteLine(msg); });
UpdateUI(resulttxt, result.ToString());
|
通过这个测试,经过1000次,创建对象并给这个Button对象的Content赋值,结果显示,弱类型在资源的消耗上的确比通过类直接实例化的结果要好。下面是测试结果:
通过类直接实例化
执行耗时: 21ms
CPU周期: 58,397,993
Gen 0: 0
Gen 1: 0
Gen 2: 0
弱类型实例化
执行耗时: 20ms
CPU周期: 58,028,617
Gen 0: 0
Gen 1: 0
Gen 2: 0
|
其实差距并不是很明显,可以忽略掉的。但是对于开销真的很大的情况下,回去会有细微的提升。
原文地址:http://luacloud.com/2012/about-performance-var-weak-type.html