8058779: Faster implementation of String.replace(CharSequence, CharSequence)

Ivan Gerasimov ivan.gerasimov at oracle.com
Sun May 31 15:21:23 UTC 2015



On 31.05.2015 13:28, Ulf Zibis wrote:
>
> Am 31.05.2015 um 08:38 schrieb Peter Levart:
>> Hi,
>>
>> Yes, this one is much easier to grasp.
>>
>> As I understand the check is to avoid overflow in calculation of 
>> StringBuilder initial capacity (newLenHint). If overflow happened, 
>> newLenHint would be negative and StringBuilder construction would 
>> fail with NegativeArraySizeException. But the calculation of newLenHint:
>>
>>     int newLenHint = value.length - targLen + replValue.length;
>>
>> ...considering the following:
>>
>>     value.length >= 0
>>     targLength >= 0
>>     replValue.length >= 0
>>     targLength <= value.length
>>
>> in case of overflow, it can only produce a negative value. So the 
>> check could simply be:
>>
>>     if (newLenHint < 0) {
>>         throw new OutOfMemoryError();
>>     }
>
> Hm, what has this situation to do with Out-Of-Memory ?
>
That should indicate that we were about to try to allocate an array of 
size > Integer.MAX_VALUE.
E.g. java.util.AbstractCollection.java:

    private static int hugeCapacity(int minCapacity) {
         if (minCapacity < 0) // overflow
             throw new OutOfMemoryError
                 ("Required array size too large");


> In other words, IMHO NegativeArraySizeException is much better here 
> and additionally saves performance.
> Additionally you could propagate it to InvalidArgumentException.
>
I don't think it is InvalidArgument case.
It just happens that the result is larger then allowed, so let's throw OOM!

Sincerely yours,
Ivan

> -Ulf
>
>
>




More information about the core-libs-dev mailing list