So from what I understand of a string vs StringBuilder is that string builder will actually modify the instance of itself while string will just make a new one. So if I understand this correctly then by using the string method for a constantly changing variable I could basically be eventually using all the memory until the computer needs to dump it to make room.
What I am doing is using an event handler to monitor serial communication. I will take in the data and parse it out plus display it in a text box. The event handler uses string to accomplish this currently. In concern for better programming and not using up all the memory when I don’t need to I am trying to clean up my code.
I started to code with string builder and begun to get the build error that StringBuilder does not contain a .contains method.
Basically I am curious if i should leave it alone? Should I approach this differently? and do I have the right understanding in that string will inevitably run me out of memory?
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
rx.AppendText(Environment.NewLine + indata);
string dataCheck = indata.ToUpper();
if (dataCheck.Contains("CONNECT") || indata.Contains("CONNECTED"))
{
cState.Text = "Connected";
connectLink();
}
if (dataCheck.Contains("NO CARRIER"))
{
cState.Text = "Disconnected";
disconnect();
}
dataCheck = null;
}
You are incorrect; using String will not (in general) cause you to run out of memory.
If you’re doing lots of concatenation, using string is less efficient, since it needs to build a new string and throw away the old string every time you concatenate.
In such scenarios, you should use a StringBuilder to build the string, then call
ToString()whenever you want to display it.Your code does not contain any concatenation, so using StringBuilder wouldn’t do any good.