Me han encargado la lectura de archivos CSV grandes (más de 300k registros) y aplicar patrones de expresiones regulares a cada registro. Siempre he sido un desarrollador de PHP y nunca he probado ningún otro idioma, pero decidí que debería hacer una inmersión e intentar hacer esto con Java, que supuse que sería mucho más rápido.Regex de Java más lento de lo esperado
De hecho, solo leer el archivo CSV línea por línea fue 3 veces más rápido en Java. Sin embargo, cuando apliqué los requisitos de expresiones regulares, la implementación de Java demostró demorar un 10-20% más que el script PHP.
Es muy posible que haya hecho algo mal en Java, porque acabo de aprender esto como lo hice hoy. A continuación están los dos guiones, cualquier consejo sería muy apreciado. Realmente me gustaría no darme por vencido con Java para este proyecto en particular.
CÓDIGO PHP
<?php
$bgtime=time();
$patterns =array(
"/SOME REGEXP/",
"/SOME REGEXP/",
"/SOME REGEXP/",
"/SOME REGEXP/"
);
$fh = fopen('largeCSV.txt','r');
while($currentLineString = fgetcsv($fh, 10000, ","))
{
foreach($patterns AS $pattern)
{
preg_match_all($pattern, $currentLineString[6], $matches);
}
}
fclose($fh);
print "Execution Time: ".(time()-$bgtime);
?>
código Java
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
public class testParser
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
String[] rawPatterns = {
"SOME REGEXP",
"SOME REGEXP",
"SOME REGEXP",
"SOME REGEXP"
};
ArrayList<Pattern> compiledPatternList = new ArrayList<Pattern>();
for(String patternString : rawPatterns)
{
Pattern compiledPattern = Pattern.compile(patternString);
compiledPatternList.add(compiledPattern);
}
try{
String fileName="largeCSV.txt";
CSVReader reader = new CSVReader(new FileReader(fileName));
String[] header = reader.readNext();
String[] nextLine;
String description;
while((nextLine = reader.readNext()) != null)
{
description = nextLine[6];
for(Pattern compiledPattern : compiledPatternList)
{
Matcher m = compiledPattern.matcher(description);
while(m.find())
{
//System.out.println(m.group(0));
}
}
}
}
catch(IOException ioe)
{
System.out.println("Blah!");
}
long end = System.currentTimeMillis();
System.out.println("Execution time was "+((end-start)/1000)+" seconds.");
}
}
No está completamente relacionado con su problema de expresión regular, pero es posible que desee consultar http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html. Es posible que encuentre que su clase CSVReader no es necesaria. No crear todas esas cadenas temporales ('nextLine' parece tener al menos 7 cadenas, pero solo necesita una) podría mejorar el rendimiento. – wolfcastle