From f1ce58ddb00100efa06f9fb95130f7a1303af248 Mon Sep 17 00:00:00 2001 From: "Nadeeka Kodituwakku [SSW]" <94897150+NadeekaJK@users.noreply.github.com> Date: Fri, 12 Apr 2024 15:20:45 +1000 Subject: [PATCH] Added 2 more benefits of sealed classes with performance stats. --- rules/seal-your-classes-by-default/rule.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/rules/seal-your-classes-by-default/rule.md b/rules/seal-your-classes-by-default/rule.md index a9106a6cd37..dc82c537db3 100644 --- a/rules/seal-your-classes-by-default/rule.md +++ b/rules/seal-your-classes-by-default/rule.md @@ -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)