关于数据库存放List

背景:

最近一直在弄公司的游戏服务器,项目由开始到现在已经过了三个月了,基本代码已经全部完成,现在正在做一波测试,测试过程中有一些性能问题,我在此记录一下,分享给大家,如果有不对的地方,也请大家指出并给出理由

数据库使用的是 sqlsever 

ORM框架为EntityFramework 6.0

语言 C#

问题描述:

由于项目需求是在开始活动时随机生成物品奖励,并且在未来的某个时间点发放,这个结构我用的是一个字典来存放,物品ID <=>  物品数量 ,但是数据库没有字典结构

初始解决方案

将该Dictionary序列化到一个string ,然后存到数据库,取出来的时候再反序列化,如下图

 后来到线上时发现了一些性能问题,通过ANTS Performance Profiler 定位到该函数

json库选用的是Newstonsoft.json ,问题应该不大

后来向相关同事请教后发现直接用分隔符来写速度会快很多,代码如下

static string Dic2String(Dictionary<int,int> GoodsDic)
{
StringBuilder build = new StringBuilder();

foreach (var item in GoodsDic)
{
build.Append(item.Key);
build.Append(",");
build.Append(item.Value);
build.Append(";");
}

return build.ToString();
}


static Dictionary<int,int> String2Dic(string str)
{
Dictionary<int, int> result = new Dictionary<int, int>();

string[] strList = str.Split(';');
for (int i = 0; i < strList.Count(); i++)
{
if(!strList[i].IsEmpty())
{
string[] keyValue = strList[i].Split(',');
result.Add(keyValue[0].ToInt(), keyValue[1].ToInt());
}
}

return result;
}

public static void Main(string[] args)
{
TestJson();
Console.ReadKey();
}

#region TestJson &

static void TestJson()
{
Dictionary<int, int> GoodsList = new Dictionary<int, int>()
{
{ 1,2},
{ 2,3},
{ 3,4},
{ 4,5},
{ 5,6},
};

string dst = Dic2String(GoodsList);
var dic = String2Dic(dst);
int Times = 100;
Console.WriteLine("测试次数{0}", Times);

Stopwatch watch = Stopwatch.StartNew();

string jsonStr = null;
for (int i = 0; i < Times; i++)
{
jsonStr = GoodsList.ToJson();
}

for (int i = 0; i < Times; i++)
{
jsonStr.FromJson<Dictionary<int,int>>();
}

watch.Stop();
Console.WriteLine("Json用时:{0}",watch.ElapsedMilliseconds);
watch.Reset();

watch.Start();
string TestStr = null;
for (int i = 0; i < Times; i++)
{
TestStr = Dic2String(GoodsList);
}

for (int i = 0; i < Times; i++)
{
String2Dic(TestStr);
}

watch.Stop();
Console.WriteLine("分隔符.用时:{0}", watch.ElapsedMilliseconds);

}

下面是测试结果对比

从结果来看,json应该是做了缓存加上Cpu的波动所以导致循环次数100次反而时间更短

从业务需求来看,缓存的意义并不大,所以采用分隔符时间更短

猜你喜欢

转载自www.cnblogs.com/ztisme/p/10032165.html