I have a pretty technical question for which I don't imagine the answer and I would like to get an advice for optimization issues.
In my sheet, I've built a lot of XML lines. Specifically, they are 389,256 lines spread across the Range("A1") -> Range("A389256").
My objective is to build a string which contains all these lines, to hence fill it into an XML file. I do this with the following piece of code:
Private Function buildFileText() As String
Dim ss As String
Dim j As Long
For j = 1 To Sheets("FileContent").Range("A1").End(xlDown).Row
ss = ss & Sheets("FileContent").Range("A" & j).Value & vbNewLine
Next j
buildFileText = ss
End Function
Basically, I just build the string starting from an empty string and adding line by line all the content of my spreadsheet.
What is scaring is the time that this piece of code takes to execute: I've put a timer right before and right after the For loop, and it took 1 hour and 44 minutes to execute.
I don't find this behavior normal, because although the high number of lines, if I try to perform the same action on (let's say) 10,000 lines, it takes not even a second. Imagining it would take a second, I would expect the whole action to take 1 second*40=40 seconds approximately. On the other hand, if it was a purely memory issue, I would have expected a stack overflow which didn't occur. So it seems the time it takes to perform each concatenation grows exponentially.
My questions:
- Would anyone explain me why this is happening?
- Does anyone have any suggestion to improve the performance of this code? Maybe I should split the concatenation in several strings (say 40 strings of 10k lines each) and concatenate each of them at a later stage?