gpt4 book ai didi

java - Perl 与 Java 哈希表性能对比

转载 作者:行者123 更新时间:2023-12-01 13:42:16 34 4
gpt4 key购买 nike

我正在尝试比较 Perl 和 Java 哈希表的性能。在 Perl 中,使用哈希并计算 100K 单词的单词数

Perl:

%words = ();
open FILE, "<", "bigfile" or die "Cannot open file: $!\n";
while(my $line = <FILE>){
chomp( $line );
$line =~ s/[[:punct:]]//g;
my @words = split /\n|\s+/, $line;
foreach my $w (@words){
$words{$w}++;
}

}
close FILE ;
for my $key ( sort( keys %words ) ) {
print "$key : $words{ $key } \n";
}

在 Java 中:

    Map<String, Integer> wordsMap = new HashMap<String, Integer>();
try{
Scanner sc = new Scanner( new File( "bigfile") );
while( sc.hasNextLine() ){
String input = sc.nextLine();
input = input.replaceAll( System.lineSeparator() , " " );
String[] inputArray = input.split("\\s+");
for(int i=0; i< inputArray.length ; i++ ){
String r = inputArray[i].replaceAll("\\p{Punct}|[^\\p{ASCII}]+", "");
if ( wordsMap.containsKey( r )){
int count = wordsMap.get( r );
wordsMap.put( r , count + 1 );
}else {
wordsMap.put( r, 1);
}
}

}
}catch(FileNotFoundException fnf ){
fnf.printStackTrace();
}

Set <String> keys = wordsMap.keySet();
TreeSet<String> sortedKeys = new TreeSet<String>(keys);

for( String key: sortedKeys){
System.out.printf("%-10s%10s\n" , key, wordsMap.get(key) );
}

当我运行上述 2 个版本时,Perl 似乎运行得更快。我在某处读到 Java Hash 与 Perl 不同。有没有办法优化Java版本?

我如何使用 Linux 时间对两者进行计时。

#> time perl count.pl
real 0m0.316s
user 0m0.236s
sys 0m0.018s

#> time java count
real 0m1.434s
user 0m1.856s
sys 0m0.181s

最佳答案

  1. 使用BufferedReader来读取行,它会更快并且读取line 方法已经chomps 行分隔符。
  2. 预编译循环中使用的正则表达式(请参阅java.util.regex.Pattern.compile)!当然,Perl 就是这样做的。
  3. 在十倍大小的文件上运行测试。
  4. 在一个非常小的文件上运行java程序2次,然后在一个更大的文件上运行2次并将第二个时间与第三个时间进行比较,这样您就知道如何启动成本是。 (通常大约 1/2 秒。)另请注意程序的第一次执行将花费更长的时间,因为类文件尚未加载到文件系统缓存中。当你有许多(数百个)类,将它们打包在 JAR 中也是值得的。

关于java - Perl 与 Java 哈希表性能对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20637458/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com