Skip to content

Apache Lucene open-source search software

Optimize byte array writes in OutputStreamIndexOutput to remove unnecessary overhead (#16119)

neoReMinDc129ceba7da2
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 4dc03ed9639..8c0022b8596 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -477,6 +477,8 @@ Optimizations
* GITHUB#16142: Optimize disjunction #docIDRunEnd to skip runs of excluded documents. (Costin Leau)
+* GITHUB#16119: Optimize byte array writes in OutputStreamIndexOutput to remove unnecessary overhead. (neoremind)
+
Bug Fixes
---------------------
* GITHUB#15754: Fix HTMLStripCharFilter to prevent tags from incorrectly consuming subsequent
diff --git a/lucene/core/src/java/org/apache/lucene/store/FSDirectory.java b/lucene/core/src/java/org/apache/lucene/store/FSDirectory.java
index 473269634b9..35adf0c60bc 100644
--- a/lucene/core/src/java/org/apache/lucene/store/FSDirectory.java
+++ b/lucene/core/src/java/org/apache/lucene/store/FSDirectory.java
@@ -369,8 +369,11 @@ public abstract class FSDirectory extends BaseDirectory {
final class FSIndexOutput extends OutputStreamIndexOutput {
/**
- * The maximum chunk size is 8192 bytes, because file channel mallocs a native buffer outside of
- * stack if the write buffer size is larger.
+ * We set the chunk size to 8192 bytes as the maximum I/O unit. Under the hood, {@link
+ * java.nio.channels.FileChannel#write} with a heap ByteBuffer allocates a thread-local
+ * temporary direct ByteBuffer and copies data into it before issuing the native write. Capping
+ * the chunk size prevents bloating that native buffer, which is cached per-thread and reused
+ * across writes.
*/
static final int CHUNK_SIZE = 8192;
diff --git a/lucene/core/src/java/org/apache/lucene/store/OutputStreamIndexOutput.java b/lucene/core/src/java/org/apache/lucene/store/OutputStreamIndexOutput.java
index 14b56a67e8a..195fb83dc74 100644
--- a/lucene/core/src/java/org/apache/lucene/store/OutputStreamIndexOutput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/OutputStreamIndexOutput.java
@@ -149,5 +149,15 @@ public class OutputStreamIndexOutput extends IndexOutput {
this.count = count + 1;
}
}
+
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException {
+ if (len > buf.length - count) {
+ super.write(b, off, len);
+ } else {
+ System.arraycopy(b, off, buf, count, len);
+ count += len;
+ }
+ }
}
}