Home > other >  Linq select list decryption is very slow
Linq select list decryption is very slow

Time:07-25

My application is MVC 5 using EF 6.2. I am decrypting certain columns while generating a list, it works but slow. Is there a better way to improve the performance of this approach?

 var mylist = await _db.vw_LearnerCourse.AsNoTracking().ToListAsync();
        var grid1 = mylist.Select(c => new
        {
            FirstName = Encryption.Decrypt5(c.FirstName),
            LastName = Encryption.Decrypt5(c.LastName)
        }).ToList();

  public static string Decrypt5(string cipherText)
        {
            if (string.IsNullOrWhiteSpace(cipherText)) return null;
            if (!string.IsNullOrWhiteSpace(cipherText))
            {
                xxxxxxxx
        }

CodePudding user response:

You may create a Decryptor instance every time when you Decrypt a string. Try create a static decryptor, and use this instance every time.

TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
                {
                    Key = key,
                    Mode = CipherMode.ECB
                };
// use this instance all time
var decryptor = des.CreateDecryptor();     
var mylist = await _db.vw_LearnerCourse.AsNoTracking().ToListAsync();
    var grid1 = mylist.Select(c => new
    {
        FirstName = Encryption.Decrypt5(decryptor,c.FirstName),
        LastName = Encryption.Decrypt5(decryptor,c.LastName)
    }).ToList();

public static string Decrypt5(ICryptoTransform decryptor, string cipherText)
    {
        if (string.IsNullOrWhiteSpace(cipherText)) return null;
        if (!string.IsNullOrWhiteSpace(cipherText))
        {
            xxxxxxxx
    }

CodePudding user response:

Perhaps try and use a concrete class instead of a dynamic object. Dynamic objects create some overhead and if there's a lot of them I guess that could be what slows it down

Like so:

class Names
{
    public string? FirstName { get; }
    public string? LastName { get; }

    public Names(string? firstName, string? lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

var grid1 = mylist.Select(c => 
    new Names(
        Encryption.Decrypt5(c.FirstName),
        Encryption.Decrypt5(c.LastName))
    .ToList();

It also looks like you're unnecessarily checking if cipherText is null or white space twice

  • Related