Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

string - VB.Net For Loop Takes So Long

I have 3 textboxes. 1st and 2nd textboxes contain approximately 40.000 to 80.000 lines of data. Each line has 6-7 characters maximum. Last checkbox has 800-1000 lines of data. These lines also has 6-7 characters. To save all these data in a single text file, I first add a time tag at beginning of each line, after a tab first textbox line written, and then second tbox, and third tbox, and then a new line. It goes on like that.

I use 3 checkboxes to understand which textboxes user wants to save. After save button clicked, this loop below starts. But it takes so long. Even user selects to save only first textbox, which means, let's say 50.000 lines, it takes almost a minute!

I tried methods like writing in a string, with a StringBuilder, with do-while loops, etc. but can't get a significant effect. I searched on internet and forum about different methods but couldn't find a way.

Is there any effective way to make it work faster?

For i = 0 To linesCount - 1
            textStr.Append(timeCount & vbTab)
            If (cbSaveOutput.Checked And Not tbOutput.Text = "") Then textStr.Append(tbOutput.Lines(i) & vbTab)
            If (cbSaveForce.Checked And Not tbForce.Text = "") Then textStr.Append(tbForce.Lines(i) & vbTab)
            If (cbSaveCrop.Checked And Not tbCroppedData.Text = "" And i < tbCroppedData.Lines.Length) Then textStr.Append(tbCroppedData.Lines(i))
            textStr.Append(Environment.NewLine)
            timeCount = Math.Round(timeCount + (1 / tbSampleRate.Text), 6)
            ProgressBar1.Increment(1)
        Next
question from:https://stackoverflow.com/questions/65626488/vb-net-for-loop-takes-so-long

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The main problem is that you are using the Lines property over and over. Lines is not "live" data. When you get the property value, the control will get the Text property value first and then split it into a new array. You are doing that for every line in every TextBox and twice for the third TextBox. That is obviously bad. As you should ALWAYS do when using the Lines property, get it once and once only and assign the value to a variable, then use that variable over and over. There are other improvements that you could make to that code but that is the major issue and will reduce the time drastically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...