¿Es StreamReader.Readline () realmente el método más rápido para contar líneas en un archivo?
Mientras miraba a mi alrededor por un tiempo, encontré algunas discusiones sobre cómo calcular la cantidad de líneas en un archivo.
Por ejemplo estos tres:
c # ¿Cómo cuento las líneas en un archivo de texto?
Determine el número de líneas dentro de un archivo de texto
¿Cómo contar líneas rápido?
Entonces, seguí adelante y terminé usando el método que parece ser el más eficiente (¿al menos de memoria?) Que pude encontrar:
private static int countFileLines(string filePath)
{
using (StreamReader r = new StreamReader(filePath))
{
int i = 0;
while (r.ReadLine() != null)
{
i++;
}
return i;
}
}
Pero esto lleva una eternidad cuando las propias líneas del archivo son muy largas. ¿Realmente no hay una solución más rápida a esto?
He estado tratando de usarStreamReader.Read()
oStreamReader.Peek()
pero no puedo (o no sé cómo) hacer que cualquiera de ellos pase a la siguiente línea tan pronto como haya "cosas" (¿texto? ¿caracteres?).
¿Alguna idea por favor?
CONCLUSIÓN / RESULTADOS (Después de ejecutar algunas pruebas basadas en las respuestas proporcionadas):
Probé los 5 métodos a continuación en dos archivos diferentes y obtuve resultados consistentes que parecen indicar que es simple.StreamReader.ReadLine()
sigue siendo una de las formas más rápidas ... Para ser honesto, estoy perplejo después de todos los comentarios y discusiones en las respuestas.
Archivo # 1:
Tamaño: 3,631 KB
Líneas: 56,870
Resultados en segundos para el archivo # 1:
0.02 -> Método de ReadLine.
0.04 -> Método de lectura.
0.29 -> Método ReadByte.
0.25 -> Readlines. Método de cuenta.
0.04 -> ReadWithBufferSize método.
Archivo # 2:
Tamaño: 14,499 KB
Líneas: 213,424.
Resultados en segundos para el archivo # 1:
0.08 -> Método ReadLine.
0.19 -> Leer método.
1.15 -> Método ReadByte.
1.02 -> Readlines.Count método.
0.08 -> ReadWithBufferSize método.
Aquí están los 5 métodos que probé en base a todos los comentarios que recibí:
private static int countWithReadLine(string filePath)
{
using (StreamReader r = new StreamReader(filePath))
{
int i = 0;
while (r.ReadLine() != null)
{
i++;
}
return i;
}
}
private static int countWithRead(string filePath)
{
using (StreamReader _reader = new StreamReader(filePath))
{
int c = 0, count = 0;
while ((c = _reader.Read()) != -1)
{
if (c == 10)
{
count++;
}
}
return count;
}
}
private static int countWithReadByte(string filePath)
{
using (Stream s = new FileStream(filePath, FileMode.Open))
{
int i = 0;
int b;
b = s.ReadByte();
while (b >= 0)
{
if (b == 10)
{
i++;
}
b = s.ReadByte();
}
return i;
}
}
private static int countWithReadLinesCount(string filePath)
{
return File.ReadLines(filePath).Count();
}
private static int countWithReadAndBufferSize(string filePath)
{
int bufferSize = 512;
using (Stream s = new FileStream(filePath, FileMode.Open))
{
int i = 0;
byte[] b = new byte[bufferSize];
int n = 0;
n = s.Read(b, 0, bufferSize);
while (n > 0)
{
i += countByteLines(b, n);
n = s.Read(b, 0, bufferSize);
}
return i;
}
}
private static int countByteLines(byte[] b, int n)
{
int i = 0;
for (int j = 0; j < n; j++)
{
if (b[j] == 10)
{
i++;
}
}
return i;
}