使用deflater对字符串进行压缩/解压缩



我想压缩/解压缩并序列化/反序列化String内容。我使用以下两个静态函数。

/**
 * Compress data based on the {@link Deflater}.
 * 
 * @param pToCompress
 *            input byte-array
 * @return compressed byte-array
 * @throws NullPointerException
 *             if {@code pToCompress} is {@code null}
 */
public static byte[] compress(@Nonnull final byte[] pToCompress) {
    checkNotNull(pToCompress);
    // Compressed result.
    byte[] compressed = new byte[] {};
    // Create the compressor.
    final Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_SPEED);
    // Give the compressor the data to compress.
    compressor.setInput(pToCompress);
    compressor.finish();
    /*
     * Create an expandable byte array to hold the compressed data.
     * You cannot use an array that's the same size as the orginal because
     * there is no guarantee that the compressed data will be smaller than
     * the uncompressed data.
     */
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream(pToCompress.length)) {
        // Compress the data.
        final byte[] buf = new byte[1024];
        while (!compressor.finished()) {
            final int count = compressor.deflate(buf);
            bos.write(buf, 0, count);
        }
        // Get the compressed data.
        compressed = bos.toByteArray();
    } catch (final IOException e) {
        LOGWRAPPER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }

    return compressed;
}
/**
 * Decompress data based on the {@link Inflater}.
 * 
 * @param pCompressed
 *            input string
 * @return compressed byte-array
 * @throws NullPointerException
 *             if {@code pCompressed} is {@code null}
 */
public static byte[] decompress(@Nonnull final byte[] pCompressed) {
    checkNotNull(pCompressed);
    // Create the decompressor and give it the data to compress.
    final Inflater decompressor = new Inflater();
    decompressor.setInput(pCompressed);
    byte[] decompressed = new byte[] {};
    // Create an expandable byte array to hold the decompressed data.
    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream(pCompressed.length)) {
        // Decompress the data.
        final byte[] buf = new byte[1024];
        while (!decompressor.finished()) {
            try {
                final int count = decompressor.inflate(buf);
                bos.write(buf, 0, count);
            } catch (final DataFormatException e) {
                LOGWRAPPER.error(e.getMessage(), e);
                throw new RuntimeException(e);
            }
        }
        // Get the decompressed data.
        decompressed = bos.toByteArray();
    } catch (final IOException e) {
        LOGWRAPPER.error(e.getMessage(), e);
    }
    return decompressed;
}

然而,与未压缩的值相比,即使我缓存解压缩的结果,它也要慢几个数量级,并且只有在真正需要内容的情况下才会解压缩这些值。

也就是说,它用于类似DOM的持久树结构和XPath查询,强制对String值进行解压缩的速度大约是原来的50倍,甚至更慢(不是真正的基准测试,只是执行单元测试)。我的笔记本电脑甚至在一些单元测试后冻结了(每次检查大约5次),因为Eclipse由于磁盘I/O太重而不再响应。我甚至将压缩级别设置为Deflater.BEST_SPEED,而其他压缩级别可能更好,也许我提供了一个可以为resources设置的配置选项参数。也许我把事情搞砸了,因为我以前没有用过放气器。我甚至只压缩字符串长度>10的内容。

编辑:在考虑将Deflater实例化提取到静态字段后,创建Deflater和inflater的实例似乎非常昂贵,因为性能瓶颈已经消失,而且可能没有微基准标记之类的东西,我看不到任何性能损失:-)我只是在使用新输入之前重置Deflater/inflater。

您是如何考虑使用更高级别的api(如Gzip)的。

下面是一个压缩示例:

public static byte[] compressToByte(final String data, final String encoding)
    throws IOException
{
    if (data == null || data.length == 0)
    {
        return null;
    }
    else
    {
        byte[] bytes = data.getBytes(encoding);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream os = new GZIPOutputStream(baos);
        os.write(bytes, 0, bytes.length);
        os.close();
        byte[] result = baos.toByteArray();
        return result;
    }
}

以下是解压缩的示例:

public static String unCompressString(final byte[] data, final String encoding)
    throws IOException
{
    if (data == null || data.length == 0)
    {
        return null;
    }
    else
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        GZIPInputStream is = new GZIPInputStream(bais);
        byte[] tmp = new byte[256];
        while (true)
        {
            int r = is.read(tmp);
            if (r < 0)
            {
                break;
            }
            buffer.write(tmp, 0, r);
        }
        is.close();
        byte[] content = buffer.toByteArray();
        return new String(content, 0, content.length, encoding);
    }
}

我们得到了非常好的性能和压缩比。

zip api也是一个选项。

您的评论是正确的答案。

通常,如果要频繁使用某个方法,则需要消除任何数据分配和复制。这通常意味着删除静态变量或构造函数的实例初始化和其他设置。

使用静态更容易,但您可能会遇到终身问题(例如,您如何知道何时清理静态——它们是否永远存在?)。

通过在构造函数中进行设置和初始化,类的用户可以确定对象的生存期并进行适当的清理。您可以在进入处理循环之前将其实例化一次,并在退出后对其进行GC。

最新更新