繁体   English   中英

Perl vs Java哈希表性能

[英]Perl vs Java hash table performance

正在尝试比较Perl和Java Hash表的性能。 在Perl中,使用哈希并计算10万个单词中的单词数

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读取行,速度会更快,并且read line方法已经chomps了行分隔符。
  2. 预编译在循环中使用的正则表达式(请参见java.util.regex.Pattern.compile )! Perl会这样做。
  3. 在大小十倍的文件上运行测试。
  4. 在一个很小的文件上运行Java程序两次,然后在一个更大的文件上运行Java程序,然后将第二个时间与第三个时间进行比较,这样您便可以了解启动成本。 (通常约为1/2秒。)还要注意,程序的第一次执行将花费较长的时间,因为类文件尚未加载到文件系统高速缓存中。 当您有很多(几百个)类时,将它们打包成一个JAR也是值得的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM