Techniqueadvanced
Decorate, sort, undecorate
Also called Schwartzian transform, decorate-sort-undecorate, DSU, cached sort key, sort by cached key, Lisp in Perl, map-sort-map.
Compute the sort key of each item once, sort the pairs of key and item, and then remove the keys. The sort then does not compute a slow key again at each comparison.
Purpose
A sort compares items many times. A sort of n items makes about n log n comparisons, so each item takes part in about 2 log n of them. When the comparison computes a key from each item, for example the size of a file, a value parsed from a line of text or a lower-case form of a long string, the sort computes the key of each item many times. For a slow key, this repeated work costs more than the sort itself. The Perl FAQ gives the rule: "If you have a complicated function needed to pull out the part you want to sort on, then don't do it inside the sort function. Pull it out first, because the sort BLOCK can be called many times for the same element"1.
The technique computes each key once. The Python HOWTO names it: "This idiom is called Decorate-Sort-Undecorate after its three steps"2. Perl programmers call it the Schwartzian transform.
Steps
- Decorate. Make a new list. For each item, put a pair or a tuple in it: the key first, then the item. The key function runs once for each item, so n times.
- Sort. Sort the new list by the key part only. The comparison now reads a stored key, which is fast.
- Undecorate. Make the result list from the item part of each pair, in the sorted order.
If the sort is not stable, or if the sort compares whole tuples, put the original position between the key and the item. Two positions are never equal, so the sort never compares two items. The Python HOWTO gives the two benefits of the position: "The sort is stable" and "The original items do not have to be comparable because the ordering of the decorated tuples will be determined by at most the first two items"2. See stable sort.
In Perl, the three steps are one expression of map, sort and map, read from the bottom up. This example sorts file names by the size of each file, and calls -s once for each name:
my @by_size =
map { $_->[1] } # 3. undecorate: keep the name
sort { $a->[0] <=> $b->[0] } # 2. sort by the stored size
map { [ -s $_, $_ ] } # 1. decorate: [size, name]
@files;
Example
In Python. The key function vowels counts the vowels in a word, and a counter shows how many times it runs. The first sort uses a comparison function that computes two keys at each comparison. The second sort does the three steps by hand. The third sort uses the key argument, which does the same steps inside the sort.
from functools import cmp_to_key
calls = 0
def vowels(word):
"""The sort key: the number of vowels. The counter shows how often it runs."""
global calls
calls += 1
return sum(ch in "aeiou" for ch in word)
words = ["banana", "kiwi", "apple", "fig", "cherry", "date", "plum", "mango"]
# Without the technique: the comparison computes two keys at each comparison.
calls = 0
slow = sorted(words, key=cmp_to_key(lambda a, b: vowels(a) - vowels(b)))
print(slow, calls)
# Decorate: put the key and the position in front of each item.
calls = 0
decorated = [(vowels(w), i, w) for i, w in enumerate(words)]
# Sort: the tuples compare by key, then by position, and never by the item.
decorated.sort()
# Undecorate: keep only the items.
fast = [w for _, _, w in decorated]
print(fast, calls)
# The key argument does the three steps inside the sort.
calls = 0
print(sorted(words, key=vowels) == fast, calls)
['fig', 'cherry', 'plum', 'kiwi', 'apple', 'date', 'mango', 'banana'] 36
['fig', 'cherry', 'plum', 'kiwi', 'apple', 'date', 'mango', 'banana'] 8
True 8
All three sorts give the same order. The comparison function calls vowels many more times than there are words. The decorated sort and the key argument call it exactly 8 times, once for each word. The words with equal counts, for example kiwi, apple, date and mango, keep their input order, because of the position in the tuple and because Python sorts are stable.
The example files do the same in JavaScript, Java, Go, Rust and C++. Each file first sorts with a key that is computed at each comparison and shows that the key runs more than 8 times, and then does the three steps and shows 8 calls.
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
static int calls = 0;
static int vowels(const std::string &w) {
++calls;
return static_cast<int>(std::ranges::count_if(w, [](char c) { return std::string("aeiou").find(c) != std::string::npos; }));
}
static void show(const std::vector<std::string> &v) {
for (const auto &w : v) std::cout << w << ' ';
}
int main() {
const std::vector<std::string> words{"banana", "kiwi", "apple", "fig", "cherry", "date", "plum", "mango"};
// A projection is called at each comparison, so the key runs many times.
auto slow = words;
std::ranges::stable_sort(slow, {}, vowels);
show(slow);
std::cout << (calls > static_cast<int>(words.size())) << '\n';
// Decorate, sort the pairs by the key, undecorate.
calls = 0;
std::vector<std::pair<int, std::string>> d;
for (const auto &w : words) d.emplace_back(vowels(w), w);
std::ranges::stable_sort(d, {}, &std::pair<int, std::string>::first);
std::vector<std::string> fast;
for (auto &p : d) fast.push_back(std::move(p.second));
show(fast);
std::cout << calls << '\n';
}
fig cherry plum kiwi apple date mango banana 1
fig cherry plum kiwi apple date mango banana 8
A projection passed to std::ranges::stable_sort runs at each comparison, so the key runs more than 8 times. A vector of pairs holds each key once, the projection &std::pair<int, std::string>::first reads the stored key, and a loop moves the words out.
import java.util.Comparator;
import java.util.List;
public class Main {
static int calls;
static int vowels(String w) {
calls++;
return (int) w.chars().filter(c -> "aeiou".indexOf(c) >= 0).count();
}
record Decorated(int key, String word) {}
public static void main(String[] args) {
List<String> words = List.of("banana", "kiwi", "apple", "fig", "cherry", "date", "plum", "mango");
// comparingInt calls the key function twice at each comparison.
calls = 0;
List<String> slow = words.stream().sorted(Comparator.comparingInt(Main::vowels)).toList();
System.out.println(slow + " " + (calls > words.size()));
// Decorate with map, sort by the stored key, undecorate with map.
calls = 0;
List<String> fast = words.stream()
.map(w -> new Decorated(vowels(w), w))
.sorted(Comparator.comparingInt(Decorated::key))
.map(Decorated::word)
.toList();
System.out.println(fast + " " + calls);
}
}
[fig, cherry, plum, kiwi, apple, date, mango, banana] true
[fig, cherry, plum, kiwi, apple, date, mango, banana] 8
Comparator.comparingInt calls the key function at each comparison. The stream map to a Decorated record computes each key once, sorted compares the stored keys, and a second map keeps the words. The stream sort is stable, because the stream from a List is ordered.
let calls = 0;
const vowels = (w) => {
calls++;
return [...w].filter((c) => "aeiou".includes(c)).length;
};
const words = ["banana", "kiwi", "apple", "fig", "cherry", "date", "plum", "mango"];
// Without the technique: two key calls at each comparison.
calls = 0;
const slow = words.toSorted((a, b) => vowels(a) - vowels(b));
console.log(slow.join(" "), calls > words.length);
// Decorate with map, sort the pairs, undecorate with map.
calls = 0;
const fast = words
.map((w) => [vowels(w), w])
.sort((a, b) => a[0] - b[0])
.map(([, w]) => w);
console.log(fast.join(" "), calls);
fig cherry plum kiwi apple date mango banana true
fig cherry plum kiwi apple date mango banana 8
The compare function calls vowels twice at each comparison, so the key runs more than 8 times. map builds pairs of key and word, sort compares the stored keys, and a second map keeps the words, so the key runs 8 times. The JavaScript sort is stable, so equal keys keep their input order.
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
var calls int
func vowels(w string) int {
calls++
n := 0
for _, c := range w {
if strings.ContainsRune("aeiou", c) {
n++
}
}
return n
}
type decorated struct {
key int
word string
}
func main() {
words := []string{"banana", "kiwi", "apple", "fig", "cherry", "date", "plum", "mango"}
// Without the technique: two key calls at each comparison.
calls = 0
slow := slices.Clone(words)
slices.SortStableFunc(slow, func(a, b string) int { return cmp.Compare(vowels(a), vowels(b)) })
fmt.Println(slow, calls > len(words))
// Decorate: one key call for each word.
calls = 0
d := make([]decorated, len(words))
for i, w := range words {
d[i] = decorated{vowels(w), w}
}
// Sort by the stored key. The stable sort keeps the input order of ties.
slices.SortStableFunc(d, func(a, b decorated) int { return cmp.Compare(a.key, b.key) })
// Undecorate.
fast := make([]string, len(d))
for i, x := range d {
fast[i] = x.word
}
fmt.Println(fast, calls)
}
[fig cherry plum kiwi apple date mango banana] true
[fig cherry plum kiwi apple date mango banana] 8
A compare function that calls vowels computes the keys many times. The slice of decorated structs holds each key once, slices.SortStableFunc compares the stored keys and keeps ties in their input order, and a loop takes out the words.
use std::cell::Cell;
fn main() {
let words = vec!["banana", "kiwi", "apple", "fig", "cherry", "date", "plum", "mango"];
let calls = Cell::new(0);
let vowels = |w: &str| {
calls.set(calls.get() + 1);
w.chars().filter(|c| "aeiou".contains(*c)).count()
};
// sort_by_key calls the key function at each comparison.
let mut slow = words.clone();
slow.sort_by_key(|w| vowels(w));
println!("{:?} {}", slow, calls.get() > words.len());
// sort_by_cached_key calls it at most once for each item.
calls.set(0);
let mut cached = words.clone();
cached.sort_by_cached_key(|w| vowels(w));
println!("{:?} {}", cached, calls.get());
// The same steps by hand: decorate, sort, undecorate.
calls.set(0);
let mut d: Vec<(usize, &str)> = words.iter().map(|w| (vowels(w), *w)).collect();
d.sort_by_key(|p| p.0);
let fast: Vec<&str> = d.into_iter().map(|p| p.1).collect();
println!("{} {}", fast == cached, calls.get());
}
["fig", "cherry", "plum", "kiwi", "apple", "date", "mango", "banana"] true
["fig", "cherry", "plum", "kiwi", "apple", "date", "mango", "banana"] 8
true 8
sort_by_key calls the key function at each comparison. sort_by_cached_key calls it once for each item and gives the same order. A vector of (key, word) pairs sorted with sort_by_key on the stored key does the same steps by hand, with 8 calls.
When to use
Use the technique when the key is slow to compute and the list is long: a key that reads a file, parses text, calls a function over the network or normalizes long strings. The time of the sort then falls from about n log n key calls to n key calls.
Do not use it for a fast key, such as a field of a record. The decorated list needs memory for n pairs and time to build and take apart, and this costs more than the key calls that it saves. Rust says of its cached form: "For simple key functions (e.g., functions that are property accesses or basic operations), sort_by_key is likely to be faster"3. Ruby says that its sort_by "generates an array of tuples containing the original collection element and the mapped value. This makes sort_by fairly expensive when the keysets are simple"4.
In a language whose sort takes a key function and computes each key once, the technique is built in. The Python HOWTO says: "Now that Python sorting provides key-functions, this technique is not often needed"2.
Pitfalls
- A key argument is not always cached. Some library functions take a key but call it at each comparison. Rust
sort_by_keyis "O(m * n * log(n)) worst-case, where the key function is O(m)"3, so it calls the key many times. JavaComparator.comparing, Goslices.SortFuncwith a key inside and C++ range projections do the same. Check the documentation, or count the calls as the example does. - Comparing the items by accident. If two keys are equal, a sort of
(key, item)tuples compares the items. This is slow, it can raise an error when the items cannot be compared, and it changes the order of ties. Put the position between the key and the item, or sort by the key part only. - Losing stability. An unstable sort of decorated pairs can reorder items with equal keys. Use a stable sort or add the position.
- Keys that change. The technique computes each key before the sort. If the key depends on data that changes during the sort, for example a file that grows, the sort uses the old value. This is usually what the program wants, but it differs from a comparator that reads the key each time.
- Memory. The decorated list holds n keys and n references. For a very large list with large keys, such as the full text of documents, the extra memory can be a problem. Use a smaller key, such as a hash or a prefix, when it gives the same order.
Tools that do it
| Language | Built in | By hand |
|---|---|---|
| Python | sort(key=f), sorted(key=f), min and max with key= |
list of (key, i, item) tuples |
| Perl | none | map, sort, map |
| Ruby | sort_by |
map, sort, map |
| Haskell | sortOn |
map, sortBy, map |
| Rust | sort_by_cached_key |
Vec<(K, T)> with sort_by_key |
| JavaScript | none | map, sort, map |
| Java | none | stream().map(...).sorted(...).map(...) with a record |
| C# | none in the documentation | Select, OrderBy, Select |
| Go | none | a slice of structs with slices.SortStableFunc |
| C++ | none | a vector of pairs with std::ranges::stable_sort |
Ruby says that sort_by "implements a Schwartzian transform which is useful when key computation or comparison is expensive"4. Haskell says: "sortOn f is equivalent to sortBy (comparing f), but has the performance advantage of only evaluating f once for each element in the input list. This is called the decorate-sort-undecorate paradigm, or Schwartzian transform"5. Rust says of sort_by_cached_key: "During sorting, the key function is called at most once per element, by using temporary storage to remember the results of key evaluation"3. When Python added the key argument, its release notes said: "Using key calls lower() method once for each element in the list while using cmp will call it twice for each comparison, so using key saves on invocations of the lower() method"6.
The name comes from Randal L. Schwartz. Wikipedia says that "The idiom is named after Randal L. Schwartz, who first demonstrated it in Perl shortly after the release of Perl 5 in 1994", and that it "is a version of a Lisp idiom known as decorate-sort-undecorate"7. The Python HOWTO also gives the name: "Another name for this idiom is Schwartzian transform, after Randal L. Schwartz, who popularized it among Perl programmers"2.
References
- perlfaq4, Perl documentation, How do I sort an array by (anything)?
- Sorting Techniques, Python documentation, Decorate-Sort-Undecorate
- Primitive Type slice, The Rust Standard Library, sort_by_key; sort_by_cached_key
- module Enumerable, Ruby documentation, sort; sort_by
- Data.List, Haskell base library, sortOn
- What's New in Python 2.4, Python documentation, Other Language Changes
- Schwartzian transform, Wikipedia, History
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag K46N2K Edit this page History Report an error Markdown