在旧的 Android 设备上写入二进制数据很慢

问题描述 投票:0回答:1

我想知道是否有人可以提供任何建议来提高旧企业 Android 5.1 设备上二进制数据写入的性能。

FileOutputStream fileOutputStream = new FileOutputStream(fileDescriptor);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
byte[] abData = new byte[1024*1024];
long lStart = System.currentTimeMillis();
for(int i= 0; i < 30; i++){
    bos.write(abData);
}
long lDuration = System.currentTimeMillis() - lStart;
utility.logDebug("OEDebug: duration (MS): " + lDuration);

执行上述测试代码写入30MB数据大约需要1.2秒。如果直接使用 FileOutputStream 而不是 BufferedOutputStream,结果实际上是相同的。我们处理的文件大小为数百 MB。每篇文章的编写时间都超过 10 秒。有什么我可以尝试提高速度的吗?

android-file
1个回答
0
投票

由于硬件限制和操作系统的老化,提高旧版 Android 5.1 设备上二进制数据写入的性能可能具有挑战性。但是,您可以尝试以下几种策略来优化写作过程:

  1. 增加缓冲区大小:默认缓冲区大小可能不是最佳的 对于您的用例。尝试增加缓冲区的大小 BufferedOutputStream 查看是否可以提高性能。实验 有不同尺寸以找到最合适的。
  2. 使用直接I/O:如果您的设备支持,使用直接I/O可以 绕过操作系统缓存并直接写入磁盘。这样可以更快 对于大文件,尽管可能并非所有设备都支持或 文件系统。
  3. 优化磁盘访问模式:一次写入大块数据 比编写许多较小的块更有效。如果可能的话, 尝试组织您的数据,以便可以写入大量连续的数据 块。
  4. 避免频繁的磁盘写入:如果您的应用程序逻辑允许, 在内存中积累数据,然后将其批量写入磁盘 less 频繁地。这可以减少与磁盘 I/O 相关的开销 操作。
FileOutputStream fileOutputStream = null;
BufferedOutputStream bos = null;

try {
    fileOutputStream = new FileOutputStream(fileDescriptor);
    
    // Increased buffer size for performance improvement
    int bufferSize = 8 * 1024 * 1024; // 8 MB
    bos = new BufferedOutputStream(fileOutputStream, bufferSize);
    
    byte[] abData = new byte[1024 * 1024]; // 1 MB
    long lStart = System.currentTimeMillis();

    for (int i = 0; i < 30; i++) {
        bos.write(abData);
    }

    long lDuration = System.currentTimeMillis() - lStart;
    utility.logDebug("OEDebug: duration (MS): " + lDuration);
} catch (IOException e) {
    // Handle exceptions appropriately
    e.printStackTrace();
} finally {
    try {
        if (bos != null) {
            bos.close();
        }
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

备注:

  1. 缓冲区大小:我已将缓冲区大小增加到 8 MB。你应该 尝试使用该值来找到最适合您的尺寸 具体用例。
  2. 异常处理:代码现在包含正确的异常处理 并确保流在finally块中关闭。
  3. 异步写入:要实现异步写入,您需要 需要将写入逻辑移至单独的线程。这可以是 使用 AsyncTask、Thread 或 Android 中的其他并发工具完成, 但它更复杂并且取决于你的整体结构 申请。
© www.soinside.com 2019 - 2024. All rights reserved.