D
DLN
Hello all,
I have a quick question regarding how best to use static strings in my C#
code that I'm hoping someone can help me with. Is there any
advantage/disadvantage from a performance standpoint to declaring all my
string constants up-front as opposed to declaring them in-line? For
example:
public class ProjectConsts
{
public const String ConstOne = "This is a test";
public const String ConstTwo = "This is also a test";
}
And then referencing them in my code:
public void SomeMethod()
{
Console.WriteLine(ProjectConsts.ConstOne);
Console.WriteLine(ProjectConsts.ConstTwo);
}
public void SomeMethod2()
{
Console.WriteLine(ProjectConsts.ConstTwo);
Console.WriteLine(ProjectConsts.ConstOne);
}
Versus just using the string literals in-line such as:
public void SomeMethod()
{
Console.WriteLine("This is a test");
Console.WriteLine("This is also a test");
}
public void SomeMethod2()
{
Console.WriteLine("This is also a test");
Console.WriteLine(This is a test");
}
My understanding of string pooling (which may be incorrect) is that in the
second form, there will only be two string references and these references
will be reused in both method calls. I find that if I declare the strings
(as well as other intrinsic types) as constants in their own class and/or
assembly, my code is easier to read and maintain, but do I incur any sort of
performance penalty by declaring the types as const and using the constant
references in place of in-line strings?
Thanks.
I have a quick question regarding how best to use static strings in my C#
code that I'm hoping someone can help me with. Is there any
advantage/disadvantage from a performance standpoint to declaring all my
string constants up-front as opposed to declaring them in-line? For
example:
public class ProjectConsts
{
public const String ConstOne = "This is a test";
public const String ConstTwo = "This is also a test";
}
And then referencing them in my code:
public void SomeMethod()
{
Console.WriteLine(ProjectConsts.ConstOne);
Console.WriteLine(ProjectConsts.ConstTwo);
}
public void SomeMethod2()
{
Console.WriteLine(ProjectConsts.ConstTwo);
Console.WriteLine(ProjectConsts.ConstOne);
}
Versus just using the string literals in-line such as:
public void SomeMethod()
{
Console.WriteLine("This is a test");
Console.WriteLine("This is also a test");
}
public void SomeMethod2()
{
Console.WriteLine("This is also a test");
Console.WriteLine(This is a test");
}
My understanding of string pooling (which may be incorrect) is that in the
second form, there will only be two string references and these references
will be reused in both method calls. I find that if I declare the strings
(as well as other intrinsic types) as constants in their own class and/or
assembly, my code is easier to read and maintain, but do I incur any sort of
performance penalty by declaring the types as const and using the constant
references in place of in-line strings?
Thanks.