0

I am working on an application which has classes like this :

public class ClassA
{
    List<ClassB> _myList = new List<ClassB>();

    public ClassA() 
    {
        _myList.Add(new ClassB("String A"));
        _myList.Add(new ClassB("String B"));
        _myList.Add(new ClassB("String C"));
        _myList.Add(new ClassB("String D"));
        _myList.Add(new ClassB("String E"));        
    }
}

Both ClassA and ClassB are used thousands of times within the application to track performance of almost every action in the application.

I am wondering if there would be any benefit of changing these strings to static or const values.

With code like this, are multiple copies of this string stored in memory, or does .Net ensure only one copy exists regardless of how many instances of ClassA and ClassB are created?

3
  • If you want to know what the benefit is then first, come up with a metric for goodness. Then come up with an acceptable level of goodness. Then measure your current level of goodness. If it is acceptably good then go work on something else; fixing things that are not broken is a waste of time,. If it is broken, then make the change, measure again, and see if there was an improvement that brought you into compliance with your goal. Coding production software is an engineering process; use an engineering discipline to answer these sorts of questions. Commented Oct 15, 2015 at 16:51
  • Since you are using this tool as part of a performance tracker, you've already got this discipline in place, so apply it to this question! Make the change and see what your performance tracker says. Commented Oct 15, 2015 at 16:53
  • Thanks @EricLippert, I should have probably specified that I was only concerned with memory use in this case as that is what I was tasked with investigating. I'm relatively new at looking into memory usage and optimization :) Commented Oct 15, 2015 at 18:12

1 Answer 1

1

There wouldn't be any benefit to that. Any string that is in your program (as opposed to something coming from user input or a file) is interned and there is only a single copy of it. You are only referencing the interned copy either way.

Here is a link to an article about string interning if you are interested in learning more: http://broadcast.oreilly.com/2010/08/understanding-c-stringintern-m.html

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I finally figured out the correct set of google keywords to use and came to the same conclusion. That said, there might be other benefits of switching to a static or const, however in terms of memory use (which is what I am tasked with investigating), this would not be an issue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.