Code Optimization in C Sharp (C#) Programming Language



What is Optimization?

The word Optimization is derived from the Latin word Optimal which means the best. Optimization is a methodology of making a system or decision fully perfect, functional, and effective.


what is code Optimization?

In terms of code, Optimization is the process of modifying code in such a way that enhances its performance, improves code quality, and makes it as efficient as possible. It requires an aspect of writing an efficient C# .Net-based application.


Need of Optimized code

A program should be optimized so that it:

  • Becomes a smaller size.

  • Consumes less memory.

  • Faster execution.

  • Performs fewer input/output operations.


Optimization Techniques

Following are some of the techniques that help to enhance the speed and efficiency of C# code and applications:


1. Replace ArrayList with List<>


ArrayList is beneficial when we store multiple types of objects within the same list.

But if we want to store the same type of data in one ArrayList, then we should prefer using List<> objects instead of to gain more performance.

ArrayList StudentList = new ArrayList();
StudentList.Add ("jaydeep");
return (int)StudentList[0] + "Astha";

Example: In the above code, it only contains a string (Student name). It also requires typecasting. Using the List<> class is much better in this case.

List<string> StudentList =   new List<string>(