OC_
OC_

Reputation: 446

Declaring variables slow down program

I have a program which uses a RichTextBox (which is part of Tab Control) and in the TextChanged event I these variable declarations:

RichTextBox programTextBox = (RichTextBox)tabControl.TabPages[tabControl.SelectedIndex].Controls[0];
int selectStart = programTextBox.SelectionStart;
int programCurrentLine = programTextBox.GetLineFromCharIndex(programTextBox.SelectionStart);
int programCurrentLineIndex = programTextBox.GetFirstCharIndexFromLine(programCurrentLine);
int programCurrentLineLength = programTextBox.Lines[programCurrentLine].Length;
string programCurrentLineText = programTextBox.Lines[programCurrentLine].ToString();

All of them are important in that particular event and I use them multiple times for multiple purposes. However, recalculating every single time slows down my program.

For example, I've noticed that if I open a somewhat large file (with my RichTextBox) and then start pressing e.g. the 'a' button, there is some noticable lag. Deleting every single piece of code except the declaration of these variables does not help at all with the lag, but also deleting the code above, completely solves the problem.

I have two questions: 1) Why do these declarations slow down that much the TextChanged event and 2) What can I do? (Is there a faster way to calculate these variables?)

Upvotes: 0

Views: 232

Answers (2)

Clayton Terry
Clayton Terry

Reputation: 31

If it is not important to recalculate on every key press you might be better off implementing a boolean variable which is set on keypress then has a timer to reset it. For example adding a 1.2 second delay on the event. I am not sure the needs of your app so that time might be a bit much.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500215

It's not the variable declarations - it's the code you're using to initialize them. I wouldn't be at all surprised to find that GetLineFromCharIndex and GetFirstCharIndexFromLine were expensive - and currently you're calling the Lines property twice.

You could probably improve matters at least slightly just by removing one of those Lines calls, simply by fetching the line first and then looking at its length:

// No need to call ToString() - Lines is a string[]
string programCurrentLineText = programTextBox.Lines[programCurrentLine];
int programCurrentLineLength = programCurrentLineText.Length;

It's a shame there isn't some way of saying "Get all the information about the position of the given index: its line, first char index from line, and the line itself" in one call :(

Upvotes: 1

Related Questions