-3

How do these two different implementations effect performance or how objects are allocated in memory?

using (ICryptoTransform encryptor = AES.CreateEncryptor())
{
    byte[] cipherBytes = encryptor.TransformFinalBlock(clearBytes, 0, clearBytes.Length);
}


byte[] cipherBytes = AES.CreateEncryptor().TransformFinalBlock(clearBytes, 0, clearBytes.Length);
Ben
  • 2,122
  • 2
  • 28
  • 48

1 Answers1

0

Whenever the object uses unmanaged resources, you need to dispose the resources, so that other programs can use that resource — Windows cannot delete this file, as it is being used by another program, that is an example of error you see when you do not release the resources being held by your program. Although there is a factor of slow performance — barely noticeable — in the using code of yours, but that is a better code provided it would also dispose any resources that your objects are holding. Nonetheless, it does create a variable, and that variable is what gets .Dispose() called.

In the second code, you would need to manually call .Dispose() function — but on what? You didn't store the variable at all. You can create the function, and the following code would try to mimic what is happening in the first block,

// Create and use.
var encryptor = AES.CreateEncryptor();
byte[] cipherBytes = encryptor.TransformFinalBlock(clearBytes, 0, clearBytes.Length);

// This function is called by "using" automatically.
encryptor.Dispose();

There are some other useful resources, for best practices in C# programming, I would recommend you give them a good thought and have a look at them. :)

using Statement (C# Reference)
Uses of using in C#

Community
  • 1
  • 1
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103