關於數據庫存放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次反而時間更短

從業務需求來看,緩存的意義並不大,所以采用分隔符時間更短

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM