RFR: 8305774: String.join(CharSequence, Iterable) can be optimized if Iterable is a Collection [v2]
Tingjun Yuan
duke at openjdk.org
Mon Apr 10 05:16:53 UTC 2023
On Mon, 10 Apr 2023 04:57:09 GMT, Glavo <duke at openjdk.org> wrote:
>> Tingjun Yuan has updated the pull request incrementally with one additional commit since the last revision:
>>
>> Add benchmark
>
> If you really don't trust a collection, then we can't do anything.
>
> Can copying the results of `toArray` ensure accuracy and security? It has too many possible problems. Maybe the size of the array is wrong, maybe it forgot to copy the contents of the collection and all it returns is an array full of nulls.
>
> To put it one step further, is its iterator necessarily correct? Perhaps its iterator implementation is also incorrect:
>
>
> class BadList implements List<Object> {
> private Object[] array;
>
> // ...
>
> public Iterator<Object> iterator() {
> // crazy implementation
> return new Iterator<Object>() {
> int i = 0;
>
> public boolean hasNext() {
> return Math.random() < 0.5;
> }
>
> public Object next() {
> if (Math.random() < 0.25) {
> array[i++] = null;
> return new Object();
> } else {
> return array[i++];
> }
> }
> };
> }
> }
>
>
> But who cares? Since its implementation is incorrect, it is normal for it to suffer for itself. We only need to prevent errors from being leaked to other places, rather than defending against all errors.
@Glavo Then why doesn't `ArrayList` trust `toArray()`? If all implementations behave correctly, then it should return an `Object[]` independent of the original collection, so `ArrayList` should trust it. Those who doesn't implement `toArray()` correctly should use these methods at their own risk, shouldn't they?
This PR modifies a class that is used by nearly every JVM code, so safety is more important than performance.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/13383#issuecomment-1501402954
More information about the core-libs-dev
mailing list