Reputation: 2226
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.
Upvotes: 3
Views: 526
Reputation: 2226
In response to one of the comments I received, I have now bench-marked this. I had assumed that the compiler would be able to inline and optimise a lambda expression so in this case the two would be virtually the same, but it turns out I was wrong.
My benchmark just confirms the answer from Yeldar Kurmangaliyev. Using lambda expressions in place of constants both increases the size of the dll that they are in and the size of the final exe, as well as having a detrimental affect of performance. This is true for both debug and release builds.
My benchmark used 4,500 constants or lambda expressions, constructing an array from them and then did some simple maths on the array and then repeated the process a hundred thousand times.
Using consts:
dll size was 94kb
exe size was 22kb
benchmark took 2 seconds.
Using lambdas:
dll size was 173kb
exe size was 115kb
benchamrk took 17 seconds.
Timings for both were improved running release over debug (0.6 seconds and 9.5 seconds). Your figures may vary, I've only included mine as a guide.
So, I'll stick with const
for constants.
Upvotes: 1
Reputation: 34234
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.
Upvotes: 4