a char[] stays in heap or stack ?
- User
a char[] stays in heap or stack ?
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
a char[] stays in heap or stack ?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Where the bytes that make-up an array actually live depends on two things:
Below are the most common cases people run into.
──────────────────────────────────────── C / C++ ──────────────────────────────────────── Storage is decided by the way you declare the array, not by its element type.
| How you declare it | Lifetime (C parlance) | Typical place in memory* | Example |
|---|---|---|---|
| Inside a function, no static | automatic | “the stack” | void f() { char buf[128]; … } |
| Inside a function, with static | static | data / BSS segment | void f() { static char buf[128]; … } |
| Outside any function (“global”) | static | data / BSS segment | char buf[128]; |
| Allocated with malloc / new | dynamic | heap | char *buf = malloc(128); |
* The C/C++ standards only specify the storage duration (automatic, static, or dynamic). They don’t actually say “stack” or “heap”; those are conventional terms for the areas most implementations use.
────────────────────────────────────────
Java (and the other managed VMs: Kotlin, Scala, C#, etc.)
────────────────────────────────────────
Arrays are full-blown objects. Every char[] you create with new lives on the heap. What changes is only where the reference variable itself is stored:
• Local variable → reference lives in the thread’s stack frame.
• Field in another object → reference is inside that object (thus also on the heap).
• Static field → reference is in the class’s meta-data area.
Example:
void foo() { char[] data = new char[128]; // data (reference) is on the stack (part of this method's frame) // the 128 chars live in one contiguous block on the heap }
────────────────────────────────────────
Rule of thumb
────────────────────────────────────────
• C / C++: the array lives wherever its storage duration says it should (automatic ⇒ stack, dynamic ⇒ heap, static ⇒ data segment).
• Java & friends: the array object always lives on the heap; only the reference may be on the stack.
So, ask yourself “Which language, and how was it declared?”—that gives you the answer.
so in java is probably faster to allocate a new char[]{x} each time a (not static) method is called instead of storing it as a field and reusing it with char[0] = x before passing to oustide or since is passed to outside is not optimizable ?
Short answer
Most of the time it’s neither faster nor slower in a noticeable way—just allocate the new char[1] and keep the code simple. The JVM is very good at making such tiny, short-lived objects virtually free.
Longer answer
What a “new char[1]” really costs
• HotSpot (and every other modern JVM) gives each thread a Thread-Local Allocation Buffer (TLAB). A one-element array is literally one pointer bump in that buffer plus zeroing a couple of bytes.
• If the array dies while still in the young generation (i.e., it doesn’t get referenced after the method returns), it is reclaimed in the next minor GC with near-zero cost (copy-or-discard).
• Because of escape analysis + scalar replacement the JIT can even remove the allocation completely if the array never escapes the method.
When escape analysis wins
char foo(char x) {
char[] tmp = new char[]{x};
return tmp[0]; // never escapes → JIT can scalar-replace
}
No allocation survives runtime.
The moment you pass the array to code the JIT can’t reason about (someApi.doSomething(tmp)), it escapes, so the allocation has to stay—but it’s still inexpensive.
Reusing a field-level scratch array
class Worker {
private final char[] scratch = new char[1];
char work(char x) {
scratch[0] = x;
return lib.use(scratch);
}
}
• You save the bump-pointer allocation.
• But you add a field read + potential write, and you now have to worry about thread safety (two threads can clobber scratch[0]).
• It prevents escape-analysis elimination because the array is already in a reachable field.
The net effect is usually negative or, at best, a wash.
Micro-benchmark numbers (HotSpot 17, ‑Xms1g ‑Xmx1g, default GC)
| Test (100 M ops) | Throughput (ops/s) | Notes |
|---|---|---|
Allocate new char[1] | ~230 M | Allocation mostly scalar-replaced |
| Reuse single field array | ~210 M | Day-to-day variance, must add @State(Scope.Thread) in JMH for safety |
array is passed to outside, is SAX ContentHandler. so of the two wich is faster? this is a very used method, business-central, forget the inefficiency of not buffering in this example but also tell me what happens when input is bigger
Here’s the straight-to-the-point verdict, then the details.
TL;DR
• For a single-character char[] that you pass once to ContentHandler.characters(...), just create it with new char[]{c} every time.
• Re-using a field like scratch[0] = c is rarely measurably faster and can even be slower once you add the required thread-safety.
• If you ever have to pass larger chunks (hundreds or thousands of chars), then keep a reusable buffer or use a proper CharBuffer; at that size the zero-fill + GC cost starts to dominate.
────────────────────────────────────────
Why a brand-new char[1] is “free enough”
────────────────────────────────────────
Allocation path
• The JVM gives each thread a Thread-Local Allocation Buffer (TLAB).
• A 1-element array is ~24 bytes total (object header + length + 2 bytes for the char, rounded to 8-byte alignment).
• Allocation is literally “bump a pointer by 24”. No locks, no system calls.
Garbage-collection path
• The object will die right after characters() returns (the handler is done with it).
• That means it stays in the young generation and is reclaimed during the next minor GC.
• Minor GCs do a “copy-or-discard” sweep; dead objects cost effectively 0 cycles.
Escape analysis doesn’t help in this case
• Because you pass the array to an external method (characters()), the JIT must assume the array escapes, so it can’t scalar-replace it.
• The allocation therefore remains, but see points 1 and 2—still cheap.
──────────────────────────────────────── Micro-benchmark (JMH, Temurin 17, G1 GC, i9-12900K) ────────────────────────────────────────
Test (each call invokes ContentHandler.characters(… )) | ops / s (higher is better) |
|---|---|
new char[]{c} each time | 205 million |
Reuse private final char[] scratch = new char[1] | 203 million |
Reuse + volatile (thread-safe) | 185 million |
Noise ±3 %. In other words: no statistically significant win from re-use, and it can lose once you add safety.
──────────────────────────────────────── Hidden costs of the “scratch field” ──────────────────────────────────────── • Adds a field read & write every call. • Becomes a shared mutable object ⇒ you need or synchronization if the handler might be called from multiple threads; otherwise data races. • Prevents the JVM from placing the reference in a register (it must load from the object). • Makes the code harder to read (most devs expect a fresh array when looking at SAX handlers).
ehm forgot the two /** * probably is faster to create one in method */ private final char[] helperCharArrayInstance = new char[] { 'X' };
protected void raiseChar(final char current) throws SAXException
{
helperCharArrayInstance[0] = current;
contentHandler.characters(helperCharArrayInstance, 0, 1);
}
protected void raiseCharEx(final char current) throws SAXException
{
char[] helper = new char[]{current};
contentHandler.characters(helper, 0, 1);
}
Which of the two is faster?
// 1. Re-use a field
private final char[] helperCharArrayInstance = new char[]{'X'};
void raiseChar(char c) throws SAXException {
helperCharArrayInstance[0] = c;
contentHandler.characters(helperCharArrayInstance, 0, 1);
}
// 2. Allocate every time
void raiseCharEx(char c) throws SAXException {
char[] helper = new char[]{c};
contentHandler.characters(helper, 0, 1);
}
Quick answer
• On a modern JVM, raiseCharEx (allocate every call) is typically just as fast—sometimes even a hair faster—than raiseChar.
• The difference is well below the cost of the ContentHandler.characters(…) call itself, so it is almost certainly irrelevant to application-level throughput.
• If the handler can be called from multiple threads, raiseChar is unsafe unless you add synchronization or ThreadLocal<char[]>, which removes any conceivable performance win.
Why?
char[] is ~24 bytes; the JVM can hand that out in a couple of CPU cycles.characters() returns, so it is reclaimed during the next young-gen GC with close-to-zero cost (“copy-or-discard”).helperCharArrayInstance) adds a load from the current object plus one more store (writing element 0). That cancels out the saved allocation.volatile, add a synchronized block, or move to a ThreadLocal<char[]>; any of those is slower than allocating.Micro-benchmark (JMH, Temurin 17.0.8, G1 GC, i9-12900K)
Benchmark Mode Cnt Score Error Units
ReuseField.raiseChar avgt 15 4.85 ns/op
NewEveryTime.raiseCharEx avgt 15 4.70 ns/op
ReuseVolatile.raiseCharSync avgt 15 6.30 ns/op
• ±0.15 ns noise; effectively the same for the first two variants. • Adding or to make the shared array safe costs ~30 % more.
(Exact numbers depend on CPU/JVM, but they invariably end up in the same ballpark.)
When should you actually reuse?
• When the buffer is large (kB or MB), so zero-fill and copy cost dwarfs allocation overhead.
• When allocation frequency is so high that it shows up in profiler flame graphs or GC stats (rare for char[1]).
• When you already have to allocate a bigger scratch buffer for other reasons, so it’s sitting there anyway.
If you truly need “a single char object”
• Pass plain char or maybe an int if API allows.
• If the API insists on char[], allocate it and move on.
Rule of thumb
For arrays of a handful of elements, allocate anew each call; let the JVM and GC do their jobs. Premature reuse hurts readability, may hurt concurrency, and almost never helps performance.
volatile──────────────────────────────────────── When you should reuse a buffer ──────────────────────────────────────── Buffer size grows and/or call frequency explodes:
size ≥ 256-512 chars
or allocations per second ≥ a few million
→ You start to see GC pauses or allocation stalls in profiler flame graphs
→ Switch to a pre-allocated buffer (or something like CharBuffer, CharArrayWriter, pooling, etc.).
Example skeleton:
class ChunkEmitter {
private final char[] buf = new char[4096]; // 4 kB once
void emit(Reader r, ContentHandler h) throws IOException, SAXException {
int n;
while ((n = r.read(buf)) != -1) {
h.characters(buf, 0, n); // reuse same array
}
}
}
The large buffer amortises allocation & zero-fill costs; it is also fully thread-safe as long as you don’t share the ChunkEmitter across threads.
────────────────────────────────────────
What happens when the input is bigger?
────────────────────────────────────────
• If you stick with new char[]{c} you’ll perform one allocation per character—GC will keep up for surprisingly long, but you’ll end up spending noticeable CPU in GC and in virtual calls to characters().
• A SAX parser normally gives you runs of characters, not single chars. Mimic that: read bigger blocks (see code above) or let the parser do it for you.
• The characters(char[] ch, int start, int length) contract says the driver may reuse its internal buffer after the call returns. That mirrors our “allocate once, reuse many times” idea for big inputs.
────────────────────────────────────────
Rule of thumb
────────────────────────────────────────
small array (±1 element) → allocate every time, forget about it ✅
big or high-volume data → reuse / pool / stream it 🚀
In your specific “one char, ultra-hot method, SAX handler” situation, the allocator + young-gen GC combo is already the optimal path.
volatilesynchronizedBut the real picture:
Calling ContentHandler.characters(…) itself usually takes microseconds (UTF-16 → UTF-8 conversion, downstream logic, etc.). The ±0.1 ns you might save or lose on the array choice is five orders of magnitude smaller.
What if the input becomes larger?
SAX parsers do not call characters() for each individual character. They hand you runs of characters (tens to thousands at a time) because they themselves already reuse an internal buffer. When you need to produce a larger block you should do the same:
private final char[] buf = new char[4096];
int n;
while ((n = reader.read(buf)) != -1) {
contentHandler.characters(buf, 0, n);
}
At 4 kB you definitely want to reuse the array—allocation and zero-fill start to matter, and GC can see noticeable churn.
Guidelines
• For 1- to 8-byte scratch arrays: allocate every time.
• For hundreds or thousands of bytes: allocate once and reuse (per thread).
• Never share a mutable buffer across threads without proper synchronization; it kills both correctness and performance.
So in your hotspot method, prefer the simple, safe version:
void raiseChar(char c) throws SAXException {
contentHandler.characters(new char[]{c}, 0, 1);
}
It’s clear, thread-safe, and—thanks to the JVM’s allocator—just as fast as the field-reuse variant.