在Java中用文件写一个非常小的字符串的最快方法是什么?

Mar*_*ker 2 java performance file-io android

我的代码需要取0到255之间的整数值,并将其作为字符串写入文件.它需要很快,因为它可以非常快速地重复调用,因此任何优化在重负载时都会变得明显.此处还有其他问题涉及将大量数据写入文件的有效方法,但少量数据如何?

这是我目前的做法:

public static void writeInt(final String filename, final int value)
{
    try
    {
        // Convert the int to a string representation in a byte array
        final String string = Integer.toString(value);
        final byte[] bytes = new byte[string.length()];
        for (int i = 0; i < string.length(); i++)
        {
            bytes[i] = (byte)string.charAt(i);
        }

        // Now write the byte array to file
        final FileOutputStream fileOutputStream = new FileOutputStream(filename);
        fileOutputStream.write(bytes, 0, bytes.length);
        fileOutputStream.close();
    }
    catch (IOException exception)
    {
        // Error handling here
    }
}
Run Code Online (Sandbox Code Playgroud)

我不认为这BufferedOutputStream会有所帮助:构建刷新缓冲区的开销对于3个字符的写入可能会适得其反,不是吗?我可以做出任何其他改进吗?

Alc*_*zar 5

我认为考虑到0-255范围要求的要求,这个效率非常高.使用缓冲的写入器效率较低,因为它会创建一些临时结构,您不需要创建这么多的字节.

static byte[][] cache = new byte[256][];
public static void writeInt(final String filename, final int value)
{
    // time will be spent on integer to string conversion, so cache that
    byte[] bytesToWrite = cache[value];
    if (bytesToWrite == null) {
        bytesToWrite = cache[value] = String.valueOf(value).getBytes();
    }

    FileOutputStream fileOutputStream = null;
    try {
        // Now write the byte array to file
        fileOutputStream = new FileOutputStream(filename);
        fileOutputStream.write(bytesToWrite);
        fileOutputStream.close();
    } catch (IOException exception) {
        // Error handling here
    } finally {
        if (fileOutputStream != null) {
            fileOutputStream.close()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)