Slightly don't pay attention, you may make your code compile a lot of unnecessary garbage

xiaoxiao2021-03-06  39

A type allows for defining multiple instance constructors, which is really very convenient during use. However, when defining these constructors, if you don't care, you may make your code compile a lot of unnecessary garbage, add the size of the assembly, not simple enough.

E.g:

Using

System;

Namespace

TestConstruct

{// /// Class2 summary description. /// public class class2 {INT32 x = 6; string s = "hello"; double d = 3.24; Byte B; public class2 () {// // Todo: Add constructor logic here //} public class2 (INT32 x) {} public class2 (string s) {}}}

Use ILDASM to see the generated IL result:

It can be seen that the three constructors have repeatedly initialized several variables, resulting in an increase in the size of the assembly after compilation.

The three constructor already account for 40 40 40 = 120 bytes.

If you are slightly modified, as shown below:

Using

System;

Namespace

TestConstruct

{// /// Class3 summary description. /// public class class3 {INT32 x = 6; string s = "hello"; double d = 3.24; byte b; public class3 () {// // Todo: Add constructor logic here //} public class3 () {} Public class3 (String s): this () {}}}

Use ILDASM to see the IL result:

It can be seen that the generated assembly size is indeed a lot. Now three constructors account for 40 7 7 = 54 bytes.

In the case of the three constructor, the size is reduced by half.

转载请注明原文地址:https://www.9cbs.com/read-116253.html

New Post(0)