7z批量压缩
我想分享一些简短而显而易见的内容-压缩在处理大量数据时效果更好。 也就是说,如果您必须压缩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);
}
}
结果如下,以字节为单位(请注意,由于存在一些随机性,因此算法无法直接比较):
算法 | 块 | 个人 |
---|---|---|
邮编 | 6590 | 10596 |
LZ4_FRAMED | 9214 | 10900 |
BZIP2 | 6663 | 12451 |
为什么会有明显的结果? 由于大多数压缩算法的工作方式–它们在原始数据中查找模式并创建这些模式的映射(非常粗略的描述)。
这有什么用? 在基础存储支持按记录压缩的大数据方案中(例如数据库或搜索引擎),如果将多个记录捆绑到一个存储/索引的记录中,则可以节省大量的磁盘空间。
但是,这不是一般有用的建议。 您应该检查特定的数据存储实现。 例如,MS SQL Server支持行和页面压缩。 Cassandra在SSTable级别上进行压缩,因此您如何构造行可能无关紧要。 当然,如果将数据存储在文件中,则将其存储在一个文件中并进行压缩比分别压缩多个文件更为有效。
磁盘空间很便宜,因此玩数据捆绑和压缩可能被视为过早的优化。 但是,在对大型数据集进行操作的系统中,这一决定可以为您节省很多存储成本。
翻译自: https://www.javacodegeeks.com/2020/09/bulk-vs-individual-compression.html
7z批量压缩