Wednesday, May 8, 2024
HomeC#Optimize Your Code: A Information To Figuring out And Avoiding Frequent C#...

Optimize Your Code: A Information To Figuring out And Avoiding Frequent C# Pitfalls


Ignoring the Dispose Methodology

That is by far the worst factor that occurs to many juniors. The IDisposable interface is applied in lots of courses. This interface has a single methodology referred to as Dispose. This methodology is used to free unmanaged sources like database connections, file streams, or unmanaged reminiscence.

In C# you may name instantly the Dispose methodology or you need to use a utilizing block.

utilizing (SqlConnection sqlConnection= new SqlConnection("connectionsstring"))
{
    sqlConnection.Question("Question the database");
} // Dispose methodology known as robotically when the block is exited

Since C# model 8, you need to use utilizing declarations like this.

utilizing SqlConnection sqlConnection= new SqlConnection("connectionsstring");
sqlConnection.Question("Question the database"); 
// Dispose methodology known as robotically when the variable sqlconnection is not used

The utilizing assertion will translate in a strive/lastly block. The utilizing assertion will robotically dispose the sources, even when an exception happens.

The best choice to establish the objects that aren’t disposed of is to make use of an extension like DisposableFixer. You may also use this code analyzer.

Not Dealing with Exceptions Accurately

One other pitfall that causes unhealthy error logging just isn’t dealing with exceptions accurately.

I’ve seen many programmers writing one of these code:

strive
{
//some code
   FileController file = new FileController("path");
    file.Open(FileAccessMode.New);
//
}
catch(FileException ex)
{
  logger.log(ex);
  throw ex; // do not do that. The stack hint won't protect and in your logs, you will notice the exception was thrown from this line.
}
catch(Exception ex)
{
  throw new Exception(ex); // do not do that 
}

Every time you want to rethrow the exception, simply use the key phrase throw:

catch(Exception ex)
{
  throw;
}

The stack hint will likely be preserved.

Overuse of Boxing and Unboxing

Boxing represents the idea of changing a price into an object reference, whereas unboxing represents the method of extracting the worth kind from the thing.

For those who overuse these ideas you’ll result in efficiency points and reminiscence consumption. This occurs since you allocate reminiscence on the heap.

ArrayList myList = new ArrayList();

for (int i = 0; i < 999999; i++)
{
    myList.Add(i); // Boxing happens right here
}

foreach (object merchandise in myList)
{
    int worth = (int)merchandise; // Unboxing happens right here
}

To unravel this challenge, attempt to use collections which have homogeneous parts. Attempt to use generic collections like Record or Dictionary.

Utilizing the incorrect assortment kind

If you’re coping with a considerable amount of information, you have to use the right assortment.

In C#, the most well-liked collections are:

  1. Arrays
  2. Lists
  3. Dictionaries
  4. Queues
  5. Stacks
  6. LinkedList
  7. HashSet
  8. SortedList
  9. ArrayList
  10. HashTable

Some sorts of collections are quicker however might require extra reminiscence. For instance, the HashSet class presents quicker operations than Record, however this comes with a better reminiscence consumption.
Each state of affairs is completely different, typically you want collections as quick as attainable, and different occasions you want ones that don’t require plenty of reminiscence.

Once you use threads just remember to use concurrent collections like Concurrent Bag or Concurrent Dictionary.

Selecting ArrayList as an alternative of Record and utilizing HashTable as an alternative of Dictionary when you might have parts of the identical kind.

ArrayList and HashTable are older and non-generic collections. Attempt to use generic collections when you may.

Utilizing Record for Massive Datasets that requires insertion and deletion

The Record class doesn’t have strategies to insert parts in the midst of the listing. Use as an alternative LinkedList class.

Utilizing Dictionary for Sequential Knowledge

Dictionaries are good when you might have key-value entry. When you want to entry information sequentially, attempt to use Lists, Sorted Lists, or Queues.

String Concatenation

Don’t use string concatenation in a loop as a result of you’ll find yourself utilizing plenty of reminiscence. Use as an alternative the StringBuilder class.

utilizing StreamReader stream = new StreamReader("TextFile1.txt");
string textual content = "";
whereas (!stream.EndOfStream)
", ","); // at each iteration a brand new reference to textual content is created

Console.WriteLine(textual content)

// Do that

utilizing StreamReader stream = new StreamReader("TextFile1.txt");
StringBuilder stringBuilder = new StringBuilder();
whereas (!stream.EndOfStream)
", ","));

Console.WriteLine(stringBuilder.ToString());

Studying all of the content material as an alternative of utilizing streams

Often whenever you cope with small recordsdata is right to make use of File.ReadAllLines methodology. Once you cope with huge recordsdata, I like to recommend you keep away from this methodology as a result of it hundreds all of the file’s content material into reminiscence. Often, you don’t must load the whole file in reminiscence.

Not utilizing asynchronous operations for Enter and Output operations

Async and await key phrases are used to implement asynchronous operations. A majority of these operations are wanted for long-running duties that suggest blocking the thread like studying a file, sending an HTTP request, or querying the database.

// Synchronous I/O operation
string textual content= File.ReadAllText("file.txt");

// Asynchronous I/O operation
string textual content= await File.ReadAllTextAsync("file.txt");

In a desktop software, async and await assist you to keep away from freezing the UI thread. In an online software, it lets you deal with extra requests.

For duties that run CPU-intensive computations attempt to use Parallel class. I’ve written an article that tells you when to make use of Parallel courses as an alternative of asynchronous duties.

LINQ Queries Pitfalls

LINQ presents you question capabilities instantly from C#. This may be difficult in the event you don’t know the best way to use it. You may enhance or unnecessarily load a server with ineffective information.

Listed below are some examples of unhealthy queries and how one can enhance it:

Utilizing Any As an alternative of Accommodates for Collections

Don’t use Any if you need to use the Accommodates methodology.

var userIds = new Record<int> { 1, 2, 3 };
var customers = dbContext.Customers.The place(u => userIds.Any(id => id == u.Id)).ToList(); // Do not

var customers = dbContext.Customers.The place(u => userIds.Accommodates(u.Id)).ToList(); // Do

Retrieving pointless information

Don’t retrieve the whole object in the event you don’t want it, particularly whenever you load many rows. Use the Choose methodology and get solely the properties that you simply want.

_context.Animals.ToList(); // do not retrieve the whole object
_context.Animals.Choose(a=>a.Title).ToList(); // retrieve solely the wanted information

Utilizing ToList too early

The decision of the tactic ToList should be the final. You don’t name the kind methodology for instance to order the objects after you retrieve it from the database.

var recentOrders = dbContext.Orders
    .The place(o => o.OrderDate > DateTime.Now.AddMonths(-3))
    .ToList() // do not name it right here!
    .OrderByDescending(o => o.OrderDate)
    .ToList();      

// do that as an alternative
var recentOrders = dbContext.Orders
    .The place(o => o.OrderDate > DateTime.Now.AddMonths(-3))
    .OrderByDescending(o => o.OrderDate)
    .ToList();

Not Utilizing Enums

If you end up coping with magic strings you must use enums as an alternative.

Magic strings are hardcoded strings which can be often used for configuration.

PictureQuality pictureQuality= new PictureQuality("Medium"); 
// .. 
if(pictureQuality.Compression=="Medium") // unhealthy design
{

}

Magic strings aren’t good as a result of they’ll simply break the code. For instance, perhaps you wish to rename the compression setting medium to one thing else. Then you want to rename it manually in the whole software. It will possibly additionally break the applying if somebody misspells the medium setting.

PictureQuality pictureQuality= new PictureQuality("Medium"); 
// .. 
if(pictureQuality.Compression=="Medum") // unhealthy design 
{

 }

For those who use enums, you keep away from a lot of these errors. You should have kind security out of the field.

PictureQuality pictureQuality= new PictureQuality(Compression.Medium); 
// .. 
if(pictureQuality.Compression==Compression.Medium){

 }

Overusing var key phrase

Don’t use the var key phrase an excessive amount of as a result of it might probably scale back the readability of the code.

var outcome = Methodology(); // what does Methodology returns?
lengthy outcome = Methodology(); // the preffered approach

Overusing Areas

I’ve seen programmers that use areas to wrap their strategies, one other area for properties and one other one for fields. Don’t ever use the areas like this. Areas are good for wrapping code that’s generated robotically or code that’s not often modified.

For those who cope with a codebase which have plenty of areas, you need to use an extension for Visible Studio that expands automaticall all of the areas.

Visual Studio extensions that automatically expands the regions

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments