groostav
08/17/2023, 3:15 PMkotlinshould delegate to specializedIntArray.sorted()
instead of generic (boxed => slower)copyOf(); j.l.Arrays.sort(int[] array)
sort(a: Array<Int>)
currently
```/**
* Returns a list of all elements sorted according to their natural sort order.
*/
public fun IntArray.sorted(): List<Int> {
return toTypedArray().apply { sort() }.asList()
}
```
should be:
```/**
* Returns a list of all elements sorted according to their natural sort order.
*/
public fun IntArray.sorted(): List<Int> {
return copyOf().apply { sort() }.asList()
}
```• should be faster... I have done no work to verify this, but the sort() code gets to skip a pair of dereferences on comparison. • puts you in the same boat as most other code WRT valhala and
IntArray.asList()
and its List<Integer>
vs List<int>
coolness
• if java ever pushes their SIMD implementation to sort
, then you could see a free perf improvement there too.
I can probably do this myself (+ other specializations) and open a PR, which would be neat, I'd love to do something like this for kotlin 🙂
If you really want performance numbers too i suppose I can boot up JMH to state my (performance) case.
edit: I also realize sort
and sorted
are different, the former does infact delegate to j.l.A.sort()
without a copy, but I still think this is a worthwhile change.
edit 2: unrelated: am i the only one who prefers (::method)
over { method() }
?ilya.gorbunov
08/17/2023, 3:56 PMget()
.
So it's not a free performance improvement, it has its compromises.Klitos Kyriacou
08/17/2023, 4:26 PMsortedArray
which returns a sorted copy of type IntArray
. What the OP is proposing can be done with
myArray.sortedArray().asList()
To return a list with the same performance characteristics as that returned by the current sorted()
function, you can do:
myArray.sortedArray().toList()
This will copy and box all elements of the array into a new List. But the overhead of doing that is already done by the current definition of sorted()
which boxes the IntArray
elements into a new Array<Int>
.groostav
08/17/2023, 4:32 PMgroostav
08/17/2023, 6:35 PMtoList()
instead of `asList()`call --given that we're working on a copy the semantics (aside from memory allocations) are identical.
• But I wouldn't, I would just use the boxing/unboxing. I think its generally accepted that boxing happens at generic-collections-function boundaries. my change would effectivey state "the backing type is int
, the requested type is int
(or at least the compiler knows what the requesting type is), the interface is Integer
, so the VM is boxing it to unbox it, which I would hope some optimization at code generation could catch. Further, after valhalla, the compiler may be able to catch it, and even without valhalla, the kotlin compiler itself may be able to generate code without the unboxing.
• regarding valhalla: https://openjdk.org/jeps/402 what is the stdlibs plan?