Most efficiant use of stringbuilder

  • Thread starter Thread starter Ryan McLean
  • Start date Start date
R

Ryan McLean

Hello everyone, I have a question for you. If I need to print 20,000
lines to a file which option is the most efficient?

(these are generated inside a datareader loop)

#1 Concatenate the data into a string variable, then write file at the
end of the loop (99.9% sure this is not it)
#2 Append the data into stringbuilder variable, then write file at the
end of the loop
#3 Append the data into stringbuilder variable, writing to the file
ever 500 or so records
#4 Don't use any variable, simply write directly to the file in every
iteration (99.9% sure this is not it either)

Thanks, I really appreciate your help. Have a great day!
Ryan
 
The fastest way--by far--is #4: Write directly to the file, using a buffered
StreamWriter.
 
Ryan,
Hello everyone, I have a question for you. If I need to print 20,000
lines to a file which option is the most efficient?
#4 Don't use any variable, simply write directly to the file in every
iteration (99.9% sure this is not it either)

If I were writing to a file, I would write to the file. So your #4 is the
correct choice.

As Russell suggests use a StreamWriter, depending on how you create your
StreamWriter it is buffered!

However I would write the routine with the assumption of a TextWriter, this
way you can use either a StreamWriter & write to a file or a StringWriter &
write to a StringBuilder.

Something like:
Private Shared Sub OutputReader(ByVal reader As Data.IDataReader, ByVal
writer As TextWriter)
Do While reader.Read()
writer.Write(reader.GetInt32(0))
writer.Write(","c)
writer.Write(reader.GetString(1))
writer.WriteLine()
Loop
End Sub

Public Shared Sub Main()
Dim reader As SqlClient.SqlDataReader
Dim writer As New IO.StreamWriter("myfile.csv")
OutputReader(reader, writer)
writer.Close()

Dim writer As New IO.StringWriter
OutputReader(reader, writer)
writer.close()
Dim s As string = writer.ToString()

End Sub

Hope this helps
Jay
 
Thank you for the responses everyone! I really appreciated your
input.

I am currently opening the file using a filestream then creating a
streamwriter with the filestream as a paratemter, I hope this is a
good way to go about it.

Looks like I'll have to benchmark the options to see which is truly
faster :)

Thanks again!
Ryan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top