当前位置: 移动技术网 > IT编程>开发语言>c# > C#中Dynamic和Dictionary性能比较

C#中Dynamic和Dictionary性能比较

2019年07月18日  | 移动技术网IT编程  | 我要评论

开发中需要传递变参,考虑使用 dynamic 还是 dictionary(准确地说是dictionary<string,object>)。

dynamic 的编码体验显著优于 dictionary,如果性能差距不大的话,我会选择使用dynamic。

搜索后没有找到类似对比数据,决定自行实验。

首先使用以下测试代码:

public void testdynamic()
{
var e = calldynamic(new { value = 0 });
int v = e.value;
}
public void testdictionary() 
{
var dict = new dictionary<string, object>();
dict["value"] = 0;
dict = calldictionary(dict);
int v = (int)dict["value"];
}
private dynamic calldynamic(dynamic test)
{
int v = test.value;
v++;
return new { value = v };
}
private dictionary<string, object> calldictionary(
dictionary<string, object> test)
{
int v = (int)test["value"];
v++;
var dict = new dictionary<string, object>();
dict["value"] = v;
return dict;
}

分别比较运行 1次、10次、100次、1000次、1e4次、1e5次、1e6次 时间

结果:

其中dynamic列和dynamic2列的数据分别是:

在一次运行中执行一步测试 和 在一次运行中连续执行所有测试

分析测试过程和数据,得到以下结论:

1.dynamic首次使用会产生一定的性能损耗

2.无论是否首次使用,使用次数达到一定量级,dynamic性能一定优于dictionary

3.一次运行中连续使用dynamic会显著拉低平均性能损耗

考虑到传递变参可能出现多个参数,以上测试不完全。

使用以下代码进行第二阶段实验:

public void invokedynamic()
{
var e = calldynamic2(
new { value1 = 0, value2 = 0l, value3 = 0f, value4 = 0.0, value5 = "test" });
int v1 = e.value1;
long v2 = e.value2;
float v3 = e.value3;
double v4 = e.value4;
string v5 = e.value5;
}
public void invokedictionary()
{
var dict = new dictionary<string, object>();
dict["value1"] = 0;
dict["value2"] = 0l;
dict["value3"] = 0f;
dict["value4"] = 0.0;
dict["value5"] = "test";
dict = calldictionary2(dict);
int v1 = (int)dict["value1"];
long v2 = (long)dict["value2"];
float v3 = (float)dict["value3"];
double v4 = (double)dict["value4"];
string v5 = (string)dict["value5"];
}
private dynamic calldynamic2(dynamic test)
{
int v1 = test.value1;
long v2 = test.value2;
float v3 = test.value3;
double v4 = test.value4;
string v5 = test.value5;
v1++;
v2++;
v3++;
v4++;
v5 += "test";
return new { value1 = v1, value2 = v2, value3 = v3, value4 = v4, value5 = v5 };
}
private dictionary<string, object> calldictionary2(
dictionary<string, object> test)
{
int v1 = (int)test["value1"];
long v2 = (long)test["value2"];
float v3 = (float)test["value3"];
double v4 = (double)test["value4"];
string v5 = (string)test["value5"];
v1++;
v2++;
v3++;
v4++;
v5 += "test";
var dict = new dictionary<string, object>();
dict["value1"] = v1;
dict["value2"] = v2;
dict["value3"] = v3;
dict["value4"] = v4;
dict["value5"] = v5;
return dict;
}

结果数据:

最后决定选择使用dynamic

有兄弟考虑可能box损耗了性能导致dictionary表现不佳,专门做了第三阶段实验,对比dynamic和dictionary<string,long>

具体数据不贴了,结果是dynamic在100000量级快一倍

以上所述是小编给大家介绍的c#中dynamic和dictionary性能比较,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网