I have some libraries that contain a large number of constants. Any application that uses the library will use some or none of those constants. So, I was wondering whether using lambda expressions (for example):
public static Milliseconds {
public static int OneSecond => 1000;
public static int TwoSeconds => 2000;
.
.
}
would be more efficient either in terms of file sizes (exe or dll) or run-time speed than:
public static Milliseconds {
public const int OneSecond = 1000;
public const int TwoSeconds = 2000;
.
.
}
I'm sure any differences would be minimal. I'm not looking to squeeze the last byte or nano-second out, I'm just curious. Thank you.
Property approach actually creates methods like get_OneSecond() which return a number which is stored in your assembly.
The second const approach does not create any members, it inlines the value of your constants wherever you use it at compile-time.
So, approach 1 will take more space and will be less "efficient", i.e. require more instructions to be executed. Of course, we talk about unnoticeable and tiny differences.
However, at the same time approach 1 gives you two things:
It gives more flexibility allowing you to encapsulate your logic. For example, one day you can make OneSecond be acquired another way (loaded from configuration / calculated / etc.) instead of being constant. These changes will not change abstraction and affect someone who use your Milliseconds class.
It lets you update your values by replacing DLL. If you use constants and replace the DLL which contains your Milliseconds class, it won't work, since constants are inlined - you will have to rebuild the whole project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With