如何“;ToString“;大量的字符数组
本文关键字:字符 数组 ToString 如何 | 更新日期: 2023-09-27 18:26:26
我有以下代码:
public static void PrependEntitiesToFile(string pathToFile)
{
char[] buffer = new char[10000];
FileInfo file = new FileInfo(pathToFile);
string renamedFile = file.FullName + ".orig";
System.IO.File.Move(file.FullName, renamedFile);
using (StreamReader sr = new StreamReader(renamedFile))
using (StreamWriter sw = new StreamWriter(file.FullName, false))
{
string entityDeclaration = "foo";
sw.Write(entityDeclaration);
string strFileContents = string.Empty;
int read;
while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
{
for (int i = 0; i < buffer.Length; i++)
{
strFileContents += buffer[i].ToString();
}
}
sw.Write(strFileContents, 0, strFileContents.Length);
}
System.IO.File.Delete(renamedFile);
}
这段代码很有效,但它的速度很慢,因为我正在循环buffer
数组中的每个字符和ToString()
。想象一下,当它摄取和复制一个823000个字符的文件时,它的速度有多慢。
有没有一种方法可以将完全填充的buffer
转换为字符串并立即添加,而不是循环遍历数组中的每个字符?或者,一般来说,有没有更快的方法?
我为这个代码感到羞愧。
实际上,这并不是它如此缓慢的原因。它很慢,因为您正在进行重复的字符串串联,这就是O(n^2)
。如果使用StringBuilder
,您会看到更好的性能。您也可以只生成一个字符数组,并调用接受这样一个数组的string
的构造函数。
但更好的是,将字符串全部跳过,只将缓冲区写入sw
。
您应该将您的字符数组传递给string
构造函数:
string strFileContents = new string(buffer);
我预计会快得多。
别这样,你太接近了。。。我想,你可以这样写输出:你好像循环了两次。。。
using (StreamReader sr = new StreamReader(renamedFile))
using (StreamWriter sw = new StreamWriter(file.FullName, false))
{
string entityDeclaration = "foo";
sw.Write(entityDeclaration);
string strFileContents = string.Empty;
int read;
while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
{
sw.Write(buffer);
}
}
我能问为什么你这么做吗。B因为看起来您的目标是在不进行其他处理的情况下逐个字符地将一个文件的内容移动到另一个文件。在这种情况下,有更好的方法。
但是,即使您确实需要读入所有内容,也可以查看File.ReadAllLines
只需使用占用缓冲区、偏移量和长度的重载,就可以完全跳过转换。
using (StreamReader sr = new StreamReader(renamedFile))
using (StreamWriter sw = new StreamWriter(file.FullName, false))
{
string entityDeclaration = "foo";
sw.Write(entityDeclaration);
string strFileContents = string.Empty;
int read;
while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
{
sw.Write( buffer, 0, read );
}
}
不要使用字符串。请改用Stringbuilder。
在.NET中,字符串是不可变的,这意味着每次更改一个字符串时,它都会生成一个副本。随着时间的推移,速度会减慢。
应该能够执行GetString()。它一次读取2048个字节来进行转换。您还可以指定一种编码类型来处理不同的字符集。
public enum EncodingType
{
ASCII,
Unicode,
UTF7,
UTF8
}
public static string ByteArrayToString(byte[] bytes)
{
return ByteArrayToString(bytes, EncodingType.Unicode);
}
public static string ByteArrayToString(byte[] bytes, EncodingType encodingType)
{
System.Text.Encoding encoding=null;
switch (encodingType)
{
case EncodingType.ASCII:
encoding=new System.Text.ASCIIEncoding();
break;
case EncodingType.Unicode:
encoding=new System.Text.UnicodeEncoding();
break;
case EncodingType.UTF7:
encoding=new System.Text.UTF7Encoding();
break;
case EncodingType.UTF8:
encoding=new System.Text.UTF8Encoding();
break;
}
return encoding.GetString(bytes);
}