- CLR.via.Csharp
- Performance
- Recommend
- Rules and Guidelines
- Benefit
- Restrictions
- Difference
- Tools
- FAQ
- Reference
When you learn CSharp language, here are many you should care performance tips. This is a note that helps your code have good performance and avoid hurting performance.
-
Unsafe
code is allowed to work directly with memory addresses and can manipulate bytes at these addresses. This is a very powerful feature and is typically useful when interoperating with unmanaged code or when you want to improve the performance of a time-critical algorithm. p17 -
The CLR’s JIT compiler does not have to compile the IL code at run time, and this can improve the application’s performance.
-
For some applications, the reduction in working set size improves performance, so using NGen can be a net win. P21
-
Because this programming paradigm is quite common, C# offers a way to simplify this code and improve its performance by providing an as operator. P96
Employee e = o as Employee; if (e != null) { // Use e within the 'if' statement. }
-
If you have an expression consisting of literals, the compiler is able to evaluate the expression at compile time, improving the application’s performance. P114
-
In some situations, value types can give better performance. In particular, you should declare a type as a value type if all the following statements are true:
- The type acts as a primitive type. Specifically, this means that it is a fairly simple type that has no members that modify any of its instance fields.
- The type doesn’t need to inherit from any other type.
- The type won’t have any other types derived from it.
-
Auto to have the CLR arrange the fields, it will be improve performance.
// Let the CLR arrange the fields to improve // performance for this value type. [StructLayout(LayoutKind.Auto)] internal struct SomeValType { private readonly Byte m_b; private readonly Int16 m_x; ... }
-
The generic collection classes offer many improvements over the non-generic equivalents.
- One of the biggest improvements is that the generic collection classes allow you to work with collections of value types without requiring that items in the collection be boxed/unboxed.
- This in itself greatly improves performance because far fewer objects will be created on the managed heap, thereby reducing the number of garbage collections required by your application.
- You will get compile-time type safety, and your source code will be cleaner due to fewer casts.
-
If the
this
and obj arguments refer to the same object, return true. This step can improve performance when comparing objects with many fields. P139 -
Compilers tend to use the call instruction when calling methods defined by a value type because value types are sealed. This implies that there can be no
polymorphism
even for theirvirtual
methods, which causes the performance of the call to be faster. -
Many compilers will never emit code to call a value type’s default constructor automatically, even if the value type offers a parameterless constructor. P186
-
To improve performance and also to avoid considering an extension method that you may not want, the C# compiler requires that you “import” extension methods. P201
-
Be aware that calling a method that takes a variable number of arguments incurs an additional performance hit unless you explicitly pass null.
-
Because a generic algorithm can now be created to work with a specific value type, the instances of the value type can be passed by value, and the CLR no longer has to do any boxing.
-
String pooling is another way to improve the performance of strings. P332
-
System.Array implement the generic equivalent of these interfaces, providing better compile-time type safety as well as better performance. P381
-
You might want to consider using an array of arrays (a jagged array) instead of a rectangular array.P386
-
The stack-allocated memory (array) will automatically be freed when the method returns; this is where we get the performance improvement. P388
-
The managed heap allocates these objects next to each other in memory, you get excellent performance when accessing these objects due to locality of reference. P507
-
The garbage collector improves performance more because it doesn’t traverse every object in the managed heap. P514
-
If you have a lot of free memory, the garbage collector won’t compact the heap; this improves performance but grows your application’s working set. P521
-
When the program needs the data, the program checks the weak reference to see if the object that contains the data is still around, and if it is, the program just uses it; the program experiences high performance. P550
-
In order to have good performance and compile-time type safety, you want to avoid using reflection as much as possible. P599
-
The field contains information that is easily calculated. In this case, you select which fields do not need to be serialized, thus improving your application’s performance by reducing the amount of data transferred. P620
-
This improves performance significantly, and avoiding context switches is something you want to achieve as often as possible when you design your code. P673
-
There are some common programming scenarios that can potentially benefit from the improved performance possible with
tasks
. P713 -
You can potentially improve the performance of this processing by using Parallel LINQ. P717
-
One of the truly great features of performing asynchronous I/O operations is that you can initiate many of them concurrently so that they are all executing in parallel. This can give your application a phenomenal performance boost. P746
-
Hybrid constructs provide the performance benefit of the primitive user-mode constructs when there is no thread contention. P789
-
To get great performance, the
lock
tries to use the Int32 and avoid using theAutoResetEvent
as much as possible. P790 -
The FCL ships with many hybrid constructs that use fancy logic to keep your threads in user mode, improving your application’s performance. P793
-
For the nocontention case to improve performance and reduce memory consumption. P816
-
The size of instances of your type is also a condition to take into account because by default, arguments are passed by value, which causes the fields in value type instances to be copied, hurting performance. P121
-
Boxing and unboxing/copy operations hurt your application’s performance in terms of both speed and memory. P126
-
At run time, the Microsoft.CSharp.dll assembly will have to load into the AppDomain, which hurts your application’s performance and increases memory consumption. P148
-
Boxing puts more pressure on the heap, forcing more frequent garbage collections and hurting performance. P166
-
The CLR would have to verify at each write that the write was not occurring to a constant object, and this would hurt performance significantly. P225
-
You do need to realize that the CLR generates native code for each method the first time the method is called for a particular data type. This will increase an application’s working set size, which will hurt performance. P270
-
If you perform a lot of string manipulations, you end up creating a lot of String objects on the heap, which causes more frequent garbage collections, thus hurting your application’s performance. P323
-
Checking strings for equality is a common operation for many applications—this task can hurt performance significantly. It is good way use function
Object.ReferenceEquals
P329 -
Dynamically growing the array hurts performance; avoid this by setting a good initial capacity. P337
-
If you construct
ASCIIEncoding
objects yourself, you are creating more objects on the heap, which hurts your application’s performance.P353 -
Allocating short-lived large objects will cause generation 2 to be col- lected more frequently, hurting performance. P520
-
Invoking a member by using reflection will also hurt performance. P590
-
A performance hit occurs when Windows context switches to another thread. P673
-
if you have more threads than CPUs, then context switching is introduced and performance dete- riorates. P674
-
Calling
Wait
or querying a task’s Result property when the task has not yet finished running will most likely cause the thread pool to create a new thread, which increases resource usage and hurts performance. P705 -
Thread synchronization would hurt performance, not requiring thread synchronization is good. P716
-
This thread synchronization lock can become a bottleneck in some applications, thereby limiting scalability and performance to some degree. P724
-
Tasks are stolen from the tail of a local queue and require that a thread synchronization lock be taken, which hurts performance a little bit. P725
-
Locks
is that they hurt performance. P756 -
Having threads transition from user mode to kernel mode and back incurs a big performance hit, which is why kernel-mode constructs should be avoided. P761
-
Each method call on a kernel object causes the calling thread to transition from managed code to native user-mode code to native kernel-mode code and then return all the way back. These transitions require a lot of CPU time and, if performed frequently, can adversely affect the overall performance of your application. P778
-
Calling
WaitOne
causes the thread to transition into the Windows’ kernel, and this is a big performance hit. P791 -
Entering and leaving a
try
block decreases the performance of the method. P799 -
Avoid using recursive locks (especially recursive reader-writer locks) because they hurt performance. P806
- If you have multiple types that can share a single version number and security settings, it is recommended that you place all of the types in a single file rather than spread the types out over separate files, let alone separate assemblies. p46
- When designing a type, you should try to minimize the number of virtual methods you define.
- First, Calling a virtual method is slower than calling a nonvirtual method.
- Second, virtual methods cannot be inlined by the JIT compiler, which further hurts performance.
- Third, virtual methods make versioning of components more brittle.
- Fourth, when defining a base type, it is common to offer a set of convenience overloaded methods.
- When normalizing strings, it is highly recommended that you use ToUpper Invariant instead of ToLowerInvariant because Microsoft has optimized the code for performing uppercase comparisons. P325
- I’d highly recommend against performing synchronous I/O operations in a server application. P719
- I will simulate creating a closed class by using the above technique of sealing the virtual methods that my class inherits.
- I always define my data fields as private and I never waver on this.
- I always define my methods, properties, and events as private and nonvir- tual.
-
Instances of the type are small (approximately 16 bytes or less).
-
Instances of the type are large (greater than 16 bytes) and are not passed as method param- eters or returned from methods.
- Source code protection
- Type safety
- Clear source
- Better performance
- You cannot turn your application's
Main
method into anasync
function. - You cannot have any
out
orref
parameters on anasync
function. - You cannot use the
await
operator inside acatch
,finally
, orunsafe
block. - You cannot take a lock that supports thread ownership or recurcion before an
await
operator and release it after theawait
operator. - Within a query expression, the
await
operator may only be used within the first collection expression. P744
- Value type objects have two representations: an unboxed form and a boxed form,Reference types are always in a boxed form.
- Value types are derived from System.ValueType.
- You can’t define a new value type or a new reference type by using a value type as a base class, you shouldn’t introduce any new virtual methods into a value type. No methods can be abstract, and all methods are implicitly sealed (can’t be overridden).
- When you assign a value type variable to another value type variable, a field-by-field copy is made. When you assign a reference type variable to another reference type variable, only the memory address is copied.
- Two or more reference type variables can refer to a single object in the heap, allowing operations on one variable to affect the object referenced by the other variable. On the other hand, value type variables are distinct objects, and it’s not possible for operations on one value type variable to affect another.
- Because unboxed value types aren’t allocated on the heap, the storage allocated for them is freed as soon as the method that defines an instance of the type is no longer active as opposed to waiting for a garbage collection.
-
Versioning
-
Performance
-
Security and predictability
The NGen.exe tool that ships with the .NET Framework can be used to compile IL code to native code when an application is installed on a user’s machine.
- Improving an application’s startup time
- Reducing an application’s working set
I always use a tool such as ILDasm.exe to view the IL code for my methods and see where the box IL instructions are. P127
Enforced by the Code Analysis tool (FxCopCmd.exe) in Visual Studio.
The easiest way to access the System Monitor control is to run PerfMon.exe.
PerfView is a free performance-analysis tool that helps isolate CPU and memory-related performance issues.
- What is an Object and a Class?
- What are the fundamental OOP concepts?
- What is Managed and Unmanaged code?
- What is an Interface?
- What are the different types of classes in C#?
- Explain code compilation in C#.
- What are the differences between a Class and Struct?
- What is the difference between the Virtual method and Abstract method?
- Explain Namespaces in C#.
- What is "using" statement in C#?
- Explain Abstraction.
- Explain Polymorphism?
- How is Exception Handing implemented in C#?
- What are C# I/O Classes? What are the common used I/O classes?
- What is StreamReader/StreamWriter classes?
- What is a Destructor in C#?
- What is an Abstract Class?
- What are Boxing and Unboxing?
- What is the difference between Continue and Break Statement?
- What is difference between finaly and finalize block?
- What is an Array? Give the syntax for a single and multi-dimensional array?
- What is a Jagged Array?
- Name some properties of Array.
- What is an Array Class?
- What is a String? What are the properties of a String Class?
- What is an Escape Sequence? Name some String escape sequences in C#
- What are Regular expressions? Search a string using regular expressions?
- What are the basic string Operations?
- What is Parsing? How to Parse a Date Time String?
- Can we use "this" command within a static method?
- **What is difference between constaints and read-only? **
- What is a Delegate?
- What are Events?
- How to use Delegates with Events?
- What are the different types of Delegates?
- What do Multicast Delegates mean?
- Explain Publisher and Subscribers in Events.
- What are Synchronization and Asynchronous operations?
- What is Reflection in C#?
- What is a Generic Class?
- Explain Get and Set Accessor properties?
- What is a Thread? What is a MultiThreading?
- Name some properties of the Thread.
- What a the different states of a Thread?
- What a Async and Await?
- What is a Deadlock?
- Explain Locks, Monitors, and Mutex Object in Threading.
- What is Race Condition?
- What is Thread Pooling?
- What is Serialization?
- What are the types of Serialization?
- Top 10 C# .NET Multithreading Interview Questions
- Managed-threading-best-practices
- Thousands of Threads and Blocking I/O
- The C10K problem
- IO Processing
- High-Performance Server Architecture
- Understanding reactor pattern with java
- C++ Vs. C# - What’s the Difference?
- Difference between semaphore and semaphoreslim?
- SpinWait vs Sleep waiting. Which one to use?
- Need to understand the usage of SemaphoreSlim?
- How to “sleep” until timeout or cancellation is requested in .NET 4.0
- Difference between decimal, float and double in .NET?
- What's the purpose of Thread.SpinWait method?
- What is a semaphore?
- Lock, mutex, semaphor, what's the difference?
- Semaphore vs. Monitors - what's the difference?
- Difference between wait() and sleep()?
- How to check possibility of deadlock in c# code
- Multiple awaits vs Task.WaitAll - equivalent?
- Await on a completed task same as task.Result?
- ConcurrentBag and lock(List) which is faster to add or remove?
- No ConcurrentList in .Net 4.0?
- What's the difference between Invoke() and BeginInvoke()?
- Task vs. TaskCompletionSource in C#
- Is the C# static constructor thread safe?
- Volatile vs. Interlocked vs. lock
-
A collection of awesome .NET libraries, tools, frameworks, and software.
-
Learn how to write any application using the C# programming language on the .NET platform.