【问题标题】:Optimization loading data in memory优化在内存中加载数据
【发布时间】:2015-08-03 22:31:05
【问题描述】:

我需要将数据从 SQLite 加载到内存中,当表包含超过 40k 个条目时,此过程会持续几分钟。 db 中的数据已加密,因此我将其解密以加载到内存中。

基本上,我是:

  • 从表中加载所有数据
  • 在读取时我解密信息并将其添加到字典中

代码:

internal static void LoadInfo(Dictionary<int, InfoMemory> dic)
{
    using (SQLiteConnection con = new SQLiteConnection(conString))
    {
        using (SQLiteCommand cmd = con.CreateCommand())
        {
            cmd.CommandText = String.Format("SELECT ID, Version, Code FROM Employee;");

            int ID, version, code;

            try
            {
                con.Open();
                using (SQLiteDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        try { ID = Convert.ToInt32(Decrypt(rdr[0].ToString())); }
                        catch { ID = -1; }
                        try { version = Convert.ToInt32(Decrypt(rdr[1].ToString())); }
                        catch { version = -1; }
                        try { code = Convert.ToInt32(Decrypt(rdr[2].ToString())); }
                        catch { code = -1; }

                        if (ID != -1)
                        {
                            if (!dic.ContainsKey(ID)) dic.Add(ID, new InfoMemory(version, code));
                        }
                    }
                    rdr.Close();
                }
            }
            catch (Exception ex) { Log.Error(ex.Message); }

            finally { con.Close(); GC.Collect(); }
        }
    }
}

我怎样才能使这个过程更快? 我尝试的一种方法是将加密数据加载到内存并在需要时解密,但如果我这样做,我会消耗更多内存。由于我在移动设备上工作,我希望尽可能降低内存消耗。

【问题讨论】:

  • 使用条件判断是否可以转换,try/catch 非常慢。
  • 您确定代码中的哪一部分是瓶颈吗?我怀疑可能是解密功能。​​
  • 我正在进行建议的更改,并会在时间和瓶颈的情况下发布结果

标签: c# memory optimization encryption windows-embedded-compact


【解决方案1】:

您可以做的一件事是;而不是使用 try/catch:

int id, version, code;

if(!int.TryParse(rdr[0], out id))
{
    id = -1;
}

if(!int.TryParse(rdr[1], out version))
{
    version = -1;
}

if(!int.TryParse(rdr[2], out code)) 
{
    code = -1;
}

【讨论】:

  • 马库斯是对的。如果捕获数据时经常发生捕获,请不要使用“try catch”,因为捕获过程非常耗时。
  • 至少,在解析之前,测试一下rdr[i]是否不为null、DBNull.Value或空字符串。
猜你喜欢
  • 2019-06-07
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-01
  • 1970-01-01
  • 2016-06-14
相关资源
最近更新 更多