大数据中批量压缩与独立压缩的比较 - Bozho


压缩在处理大量数据时效果更好,玩数据压缩可能被视为过早的优化。但是,在对大型数据集进行操作的系统中,这一决定可以为您节省很多存储成本。
如果您必须压缩100个句子,则最好批量压缩它们,而不是一次压缩一个句子。让我说明一下:

public static void main(String[] args) throws Exception {
    List<String> sentences = new ArrayList<>();
    for (int i = 0; i < 100; i ++) {
        StringBuilder sentence = new StringBuilder();
        for (int j = 0; j < 100; j ++) { 
          sentence.append(RandomStringUtils.randomAlphabetic(10)).append(" "); 
        } 
        sentences.add(sentence.toString()); 
    } 
    byte[] compressed = compress(StringUtils.join(sentences,
". ")); 
    System.out.println(compressed.length); 
    System.out.println(sentences.stream().collect(Collectors.summingInt(sentence -> compress(sentence).length)));
}

compress方法使用commons-compress轻松生成多种压缩算法的结果:

public static byte[] compress(String str) {
   if (str == null || str.length() == 0) {
       return new byte[0];
   }
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   try (CompressorOutputStream gzip = new CompressorStreamFactory()
           .createCompressorOutputStream(CompressorStreamFactory.GZIP, out)) {
       gzip.write(str.getBytes("UTF-8"));
       gzip.close();
       return out.toByteArray();
   } catch (Exception ex) {
       throw new RuntimeException(ex);
   }
}

结果如下,
算法        批量     单独
[code]GZIP        6590    10596
LZ4_FRAMED    9214    10900
BZIP2        6663    12451
[/code]

批量压缩明显快于单独压缩!
为什么会有明显的不同结果?由于大多数压缩算法的工作方式–它们在原始数据中查找模式并创建这些模式的映射(非常粗略的描述)。
这有什么用?在基础存储支持按记录压缩的大数据方案中(例如数据库或搜索引擎),如果将多个记录捆绑到一个存储/索引的记录中,则可以节省大量磁盘空间。
但是,这不是一般有用的建议。您应该检查特定的数据存储实现。例如,MS SQL Server支持行和页面压缩。Cassandra确实在SSTable级别进行压缩,因此您如何构造行可能无关紧要。当然,如果将数据存储在文件中,则将其存储在一个文件中并进行压缩比分别压缩多个文件更有效。