Skip to content

Commit

Permalink
Added 2 more benefits of sealed classes with performance stats.
Browse files Browse the repository at this point in the history
  • Loading branch information
NadeekaJK authored Apr 12, 2024
1 parent 1a8be58 commit f1ce58d
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions rules/seal-your-classes-by-default/rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,22 @@ Watch this video by Nick Chapsas, to see the performance benefits of sealing you

`youtube: https://www.youtube.com/embed/d76WWAD99Yo`
**Video: Why all your classes should be sealed by default in C# by Nick Chapsas (11 min)**

### Avoid unnecessary covariance checks in Array

Arrays in .NET are covariant. This means arrays enable implicit conversion of an array of a more derived type to an array of a less derived type.
This operation is not type safe. To make sure it’s type safe JIT checks the type of the object before an item is assigned which is a performance cost.
When the array is an array of sealed types, JIT knows there won’t be any covariance involved when sealed types are used, so it skips covariance checks.
This improves performance with arrays.

![Figure: Array covariance - sealed Vs non-sealed. See the next figure for performance results.](ArrayCovariance_code.png)

![Figure: Performance results show arrays with sealed types show improved performance compared to arrays with non-sealed types.](ArrayCovariance_PerfResults.png)

### Skip hierarchy checks of inheritance in runtime for is/as cast operations

During a cast operation, JIT needs to know the type of the object at runtime. When casting to a non-sealed type, the runtime must check all the types in the inheritance hierarchy, which can be time consuming. When casting to a sealed type, the runtime only checks the type of the object. Hence the performance gain.

![Figure: Casting sealed Vs non-sealed. See the next figure for performance results.](Casting_code.png)

![Figure: Performance results show casting of sealed has improved performance compared to non-sealed.](Casting_PerfResult.png)

0 comments on commit f1ce58d

Please sign in to comment.