What is more expensive, storing multiple strings, or one large concatanated string?

M0ment 41 Reputation points
2022-01-09T12:37:23.393+00:00

Hello.
Say I have a class, that stores information on a file. You have the path, the name of the file, and the extension. Would it be better to store a string for each of those, like this:

public class File {
    public string path;
    public string name;
    public string extension;

    public string FullName { get { return path + '\\' + name + extension; } }
}

Or, just storing the FullName and having a property for each of the things, like this:

public class File {
    public string fullName;

    public string Path { get { return fullName.Remove(fullName.LastIndexOf('\\')); } }
    //etc...
}

Thank you!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,364 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,161 Reputation points
    2022-01-09T13:08:25.047+00:00

    String are immutable in C#. Every concatenation or string function creates a new string.

    Strings (C# Programming Guide)
    $ - string interpolation (C# reference)
    @ (C# Reference)

    If the application use case requires path, name, and extension in then it makes more sense to leave these items as separate properties. Use a backing field for the FullName property so the concatenation is done once.

    Properties (C# Programming Guide)

        class Program  
        {  
            static void Main(string[] args)  
            {  
                File file = new File()  
                {  
                    Path = @"C:\temp",  
                    Name = "myfile",  
                    Extension = "txt"  
                };  
      
                Console.WriteLine(file.FullName);  
            }  
      
        }  
      
        public class File  
        {  
            public string Path { get; init; }  
            public string Name { get; init; }  
            public string Extension { get; init; }  
      
            private string _fullName;  
            public string FullName   
            {   
                get   
                {   
                    if(String.IsNullOrEmpty(_fullName))  
                    {  
                        _fullName = @$"{Path}\{Name}.{Extension}";  
                    }  
                    return _fullName;  
                }   
            }  
        }  
    

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 57,731 Reputation points
    2022-01-09T16:59:39.967+00:00

    It depends on the use cases. Parsing is more expensive than concatenation. But which methods does the code call more, the parts or the full?

    Also is this code called enough to even worry about optimization?

    0 comments No comments