据说在串联方面char[]
表现更好StringBuilder
并且StringBuilder
表现更好string
。
StringBuilder
在我的测试中,使用和string
循环内部没有显着差异。实际上char[]
是最慢的。
我正在针对具有 44 列和 130,000 行的同一个表进行测试,查询是 select * from test
有人可以帮我看看我是否做错了什么?
以下是代码
//fetchByString(rd, fldCnt, delimiter, sw); // duration: 3 seconds
//fetchByBuilder(rd, fldCnt, delimiter, sw, rsize); // duration: 3 seconds
//fetchByCharArray(rd, fldCnt, delimiter, sw, rsize); // duration: 7 seconds
private void fetchByString(OracleDataReader pReader, int pFldCnt, string pDelimiter, StreamWriter pWriter)
{
while (pReader.Read())
{
string[] s = new string[pFldCnt];
for (Int32 j = 0; j < pFldCnt; j++)
{
if (pReader.IsDBNull(j))
{
s[j] = "";
}
else
{
s[j] = pReader.GetValue(j).ToString(); // correct value
}
}
pWriter.WriteLine(string.Join(pDelimiter, s));
}
}
private void fetchByBuilder(OracleDataReader pReader, int pFldCnt, string pDelimiter, StreamWriter pWriter, int pRowSzie)
{
StringBuilder sb = new StringBuilder(pRowSzie);
while (pReader.Read())
{
for (Int32 j = 0; j < pFldCnt; j++)
{
if (pReader.IsDBNull(j))
{
//sb.Append("");
sb.Append(pDelimiter);
}
else
{
sb.Append(pReader.GetValue(j).ToString()); // correct value
sb.Append(pDelimiter);
}
}
pWriter.WriteLine(sb.ToString());
sb.Clear();
}
}
private void fetchByCharArray(OracleDataReader pReader, int pFldCnt, string pDelimiter, StreamWriter pWriter, int pRowSzie)
{
char[] rowArray;
int sofar;
while (pReader.Read())
{
rowArray = new char[pRowSzie];
sofar = 0;
for (Int32 j = 0; j < pFldCnt; j++)
{
if (pReader.IsDBNull(j))
{
pDelimiter.CopyTo(0, rowArray, sofar, pDelimiter.Length);
sofar += pDelimiter.Length;
}
else
{
pReader.GetValue(j).ToString().CopyTo(0, rowArray, sofar, pReader.GetValue(j).ToString().Length);
sofar += pReader.GetValue(j).ToString().Length;
pDelimiter.CopyTo(0, rowArray, sofar, pDelimiter.Length);
sofar += pDelimiter.Length;
}
}
string a = new string(rowArray).TrimEnd('\0');
pWriter.WriteLine(a);
}
}