Skip to content

Commit 02e0336

Browse files
authored
Apply NewLine in StreamWriter, improve performance (#51)
1 parent e89f687 commit 02e0336

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

System.IO.Streams/StreamWriter.cs

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,13 @@ namespace System.IO
1313
/// </summary>
1414
public class StreamWriter : TextWriter
1515
{
16-
private const string c_NewLine = "\r\n";
1716
private const int c_BufferSize = 0xFFF;
1817

1918
private bool _disposed;
2019
private byte[] _buffer;
2120
private int _curBufPos;
21+
// must equal TextWriter._InitialNewLine
22+
private byte[] _newLineBytes = Encoding.UTF8.GetBytes("\r\n");
2223

2324
/// <summary>
2425
/// Gets the underlying stream that interfaces with a backing store.
@@ -32,6 +33,20 @@ public class StreamWriter : TextWriter
3233
/// <value>The Encoding specified in the constructor for the current instance, or <see cref="UTF8Encoding"/> if an encoding was not specified.</value>
3334
public override Encoding Encoding => Encoding.UTF8;
3435

36+
/// <inheritdoc/>
37+
public override string NewLine
38+
{
39+
get
40+
{
41+
return base.NewLine;
42+
}
43+
set
44+
{
45+
base.NewLine = value;
46+
_newLineBytes = this.Encoding.GetBytes(value);
47+
}
48+
}
49+
3550
/// <summary>
3651
/// Initializes a new instance of the <see cref="StreamWriter"/> class for the specified stream by using UTF-8 encoding and the default buffer size.
3752
/// </summary>
@@ -160,13 +175,16 @@ public override void Write(char value)
160175
}
161176

162177
/// <inheritdoc/>
163-
public override void WriteLine()
178+
public override void Write(string value)
164179
{
165-
byte[] tempBuf = Encoding.GetBytes(c_NewLine);
166-
180+
byte[] tempBuf = Encoding.GetBytes(value);
167181
WriteBytes(tempBuf, 0, tempBuf.Length);
182+
}
168183

169-
return;
184+
/// <inheritdoc/>
185+
public override void WriteLine()
186+
{
187+
WriteBytes(_newLineBytes, 0, _newLineBytes.Length);
170188
}
171189

172190
/// <summary>
@@ -179,9 +197,8 @@ public override void WriteLine()
179197
/// </remarks>
180198
public override void WriteLine(string value)
181199
{
182-
byte[] tempBuf = Encoding.GetBytes(value + c_NewLine);
183-
WriteBytes(tempBuf, 0, tempBuf.Length);
184-
return;
200+
Write(value);
201+
WriteLine();
185202
}
186203

187204
internal void WriteBytes(

0 commit comments

Comments
 (0)