Skip to content

FileSource/FileSink on native are doubly buffered #1807

Description

@MohammedKHC

FileSource and FileSink are always wrapped in Okio.buffer() by the caller — that's the entire point of the unbuffered Source/Sink layer. So the FILE* stdio buffer sitting between Okio's own Buffer and the kernel is pure waste: it adds a redundant memcpy through libc's internal 4–8 KB buffer on every segment transfer.

The JVM gets this right. The call chain is:

JvmOkio.kt wraps a raw FileInputStream/FileOutputStream, not a BufferedInputStream/BufferedOutputStream:
https://github.com/square/okio/blob/f806620cd18dcbafa4eb3ac484ae7985fd92dba9/okio/src/jvmMain/kotlin/okio/JvmOkio.kt#L178-L187

FileInputStream.readBytes calls straight into readBytes in io_util.c:
https://github.com/openjdk/jdk/blob/3c1af6b9c8f3f8b56c7fcfae5df250840fbf7cb4/src/java.base/share/native/libjava/FileInputStream.c#L69-L73

readBytes calls IO_Read directly on the raw fd with a stack-allocated bounce buffer — no FILE*, no stdio:
https://github.com/openjdk/jdk/blob/3c1af6b9c8f3f8b56c7fcfae5df250840fbf7cb4/src/java.base/share/native/libjava/io_util.c#L146

On Unix, IO_Read/IO_Write resolve to bare read(2)/write(2) syscalls:
https://github.com/openjdk/jdk/blob/3c1af6b9c8f3f8b56c7fcfae5df250840fbf7cb4/src/java.base/unix/native/libjava/io_util_md.c#L192

So on JVM every InputStream.read(byte[], off, len) goes Java → JNI → IO_Read → read(2). On native the same operation goes Kotlin → fread → libc internal buffer → read(2), with a pointless copy through a buffer that does nothing Okio isn't already doing.

The fix is to replace fopen/FILE* in variantSource/variantSink with open(2) and sequential read(2)/write(2) on the resulting fd, matching what the JVM has always done.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions