@@ -1303,6 +1303,7 @@ impl<T> [T] {
1303
1303
/// Sorts the slice with a key extraction function.
1304
1304
///
1305
1305
/// During sorting, the key function is called only once per element.
1306
+ ///
1306
1307
/// This sort is stable (i.e. does not reorder equal elements) and `O(m n + n log n)`
1307
1308
/// worst-case, where the key function is `O(m)`.
1308
1309
///
@@ -1329,7 +1330,10 @@ impl<T> [T] {
1329
1330
where F : FnMut ( & T ) -> B , B : Ord
1330
1331
{
1331
1332
let mut indices: Vec < _ > = self . iter ( ) . map ( f) . enumerate ( ) . map ( |( i, k) | ( k, i) ) . collect ( ) ;
1332
- indices. sort ( ) ;
1333
+ // The elements of `indices` are unique, as they are indexed, so any sort will be stable
1334
+ // with respect to the original slice. We use `sort_unstable` here because it requires less
1335
+ // memory allocation.
1336
+ indices. sort_unstable ( ) ;
1333
1337
for i in 0 ..self . len ( ) {
1334
1338
let mut index = indices[ i] . 1 ;
1335
1339
while index < i {
@@ -1414,8 +1418,11 @@ impl<T> [T] {
1414
1418
/// Sorts the slice with a key extraction function, but may not preserve the order of equal
1415
1419
/// elements.
1416
1420
///
1421
+ /// Note that, currently, the key function for `sort_unstable_by_key` is called multiple times
1422
+ /// per element, unlike `sort_stable_by_key`.
1423
+ ///
1417
1424
/// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1418
- /// and `O(n log n)` worst-case.
1425
+ /// and `O(m n log m n)` worst-case, where the key function is `O(m)` .
1419
1426
///
1420
1427
/// # Current implementation
1421
1428
///
@@ -1425,8 +1432,8 @@ impl<T> [T] {
1425
1432
/// randomization to avoid degenerate cases, but with a fixed seed to always provide
1426
1433
/// deterministic behavior.
1427
1434
///
1428
- /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1429
- /// slice consists of several concatenated sorted sequences .
1435
+ /// Due to its key calling strategy, `sort_unstable_by_key` is likely to be slower than
1436
+ /// `sort_by_key` in cases where the key function is expensive .
1430
1437
///
1431
1438
/// # Examples
1432
1439
///
0 commit comments