【问题标题】:How to increase performance of store and load file如何提高存储和加载文件的性能
【发布时间】:2014-05-08 22:50:38
【问题描述】:

我用这个来存储

FileOutputStream savedList = new FileOutputStream(....);
                GZIPOutputStream gz = new GZIPOutputStream(savedList);
                ObjectOutputStream oosList = new ObjectOutputStream(
                        gz);
                oosList.writeObject(input);

                oosList.close();

这个要加载

 FileInputStream savedSerializable = new FileInputStream(....);

            GZIPInputStream gz = new GZIPInputStream(savedSerializable);
            ObjectInputStream oisList = new ObjectInputStream(
                    gz);
            savedList = (Serializable) oisList.readObject();

如何提高存储和加载速度? BufferedInputStreamBufferedOutputStream 可以提高性能吗?如果是,我应该如何正确使用和配置这些(平均文件大小为 6 到 50mb)?

【问题讨论】:

    标签: java android file-io fileinputstream fileoutputstream


    【解决方案1】:

    您可以使用 Kryo (https://github.com/EsotericSoftware/kryo),它可以更快地执行序列化并减少文件大小,从而提高总加载/保存的速度。

    编辑

    以下代码将为您提供有关如何使用它的提示

        Kryo k = new Kryo();
        Object[] input = new Object[]{/*...*/};
    
        //make serialization faster using code generation
        k.setAsmEnabled(true);
        //allow you to serializae objects of classes that does not have a default constructor
        k.setInstantiatorStrategy(new StdInstantiatorStrategy());
    
        //you should now register all the clsses types that you intend to use with kryo
        k.register(A.class);
        k.register(B.class);
        //...
        //now you can write your objects this way:
        try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(DATA_STORE_LOCATION));
             Output out = new UnsafeOutput(zip)) {
            k.writeObject(out, input);
        }
    
        //and read it this way
        try (ZipInputStream zip = new ZipInputStream(new FileInputStream(DATA_STORE_LOCATION));
                Input in = new UnsafeInput(zip)){
            Object[] store = k.readObject(in, Object[].class);
        }
    

    【讨论】:

    • 你能给我一个样品和更多的细节吗?会影响 RAM 消耗吗?
    • @AndreaF 看到我更新的答案,我相信它会减少 RAM 消耗,因为它读取\写入更少的数据,因此使用更少的内存**请注意,我不确定 UnsafeInput 和 UnsafeOutput 类可以在 android 上工作 - 你在库中有不同的选项(FastInput / FastOutput)应该可以工作..
    • 我得到错误无法在 StdInstantiatorStrategy() 解析符号
    • 此外,在try (ZipInputStream....相对于语言也会出现编译错误,尝试使用Java 7中支持的资源,该资源仅在android API级别19中支持
    猜你喜欢
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2017-06-20
    相关资源
    最近更新 更多