RFR: 8355177: Speed up StringBuilder::append(char[]) via Unsafe::copyMemory [v8]

Raffaello Giulietti rgiulietti at openjdk.org
Mon Jul 28 12:49:01 UTC 2025


On Mon, 28 Jul 2025 01:11:26 GMT, Shaojin Wen <swen at openjdk.org> wrote:

>> I prefer to calculate an ARRAY_CHAR_SHIFT in the constant like ShortVector does, like this
>> 
>> static final int ARRAY_CHAR_SHIFT 
>>                    = 31 - Integer.numberOfLeadingZeros(Unsafe.ARRAY_CHAR_INDEX_SCALE);
>> 
>>         Unsafe.getUnsafe().copyMemory(
>>                 ca,
>>                 Unsafe.ARRAY_CHAR_BASE_OFFSET + (long) off << ARRAY_CHAR_SHIFT,
>>                 val,
>>                 Unsafe.ARRAY_CHAR_BASE_OFFSET + (long) off << ARRAY_CHAR_SHIFT,
>>                 (long) (end - off) << ARRAY_CHAR_SHIFT);
>
> String uses `<< coder` in many places. I think the following way of writing is also good:
> 
>         Unsafe.getUnsafe().copyMemory(
>                 ca,
>                 Unsafe.ARRAY_CHAR_BASE_OFFSET + (long) off << String.UTF16,
>                 val,
>                 Unsafe.ARRAY_CHAR_BASE_OFFSET + (long) off << String.UTF16,
>                 (long) (end - off) << String.UTF16);

I agree that we can expect arrays to be laid out as a contiguous chunk of memory with the intuitively expected element size.
_But..._ AFAIK this is not specified anywhere in the JVMS, although it is true that it is tacitly assumed in many low-level parts of the codebase. So, in this sense, I'm fine with your code.

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/24773#discussion_r2236290641


More information about the core-libs-dev mailing list