Is there any performance benefit in using const or readonly modifiers on fields in c#?
Is there any performance benefit to using const
or reado开发者_Go百科nly
fields compared to regular, modifiable fields, when only using private variables.
For example:
public class FooBaar
{
private string foo = "something";
private const string baar = "something more"
public void Baaz()
{
//access foo, access baar
}
}
In the above example you can see there are two fields: foo
and baar
. Both are unaccessible outside the the class, so how come many people prefer to use const
here, instead of just private
. Does the const
provide any performance benefit?
This question was previously closed by the community, because people misunderstood this question as "What is the difference between const
and readonly
in terms of performance?", which has been answered here: What is the difference between const and readonly?.
const
or readonly
over not using any of them". A const will be optimized by the compiler to be inlined into your code, a readonly cannot be inlined. However you cannot make constants of all types - so here you must make them readonly.
So if you need a constant value in your code, you should first look to use a const if possible, if not then readonly is there to allow you to have the safety, but not the performance benefits.
As an example:
public class Example
{
private const int foo = 5;
private readonly Dictionary<int, string> bar = new Dictionary<int, string>();
//.... missing stuff where bar is populated
public void DoSomething()
{
Console.Writeline(bar[foo]);
// when compiled the above line is replaced with Console.Writeline(bar[5]);
// because at compile time the compiler can replace foo with 5
// but it can't do anything inline with bar itself, as it is readonly
// not a const, so cannot benefit from the optimization
}
}
I wouldn't worry too much about the performance of these constructs until you encounter a critical piece of code that requires you to make such measurements. They're there to ensure correctness of code, not for performance reasons.
精彩评论