extsort
A high-performance external sorting library for Go that enables sorting of arbitrarily large datasets that don't fit entirely in memory. The library operates on channels and uses temporary disk storage to handle datasets larger than available RAM.
Features
- Memory Efficient: Sorts datasets of any size using configurable memory limits
- High Performance: Optimized for throughput with parallel sorting and merging
- Generic Support: Modern Go generics for type-safe operations
- Legacy Compatible: Maintains backward compatibility with interface-based API
- Cross-Platform: Works on Unix, Linux, macOS, and Windows
- Channel-Based: Integrates seamlessly with Go's concurrency patterns
Installation
go get github.com/lanrat/extsort
Quick Start
IMPORTANT: All input channels must be closed after all data has been sent. The Sort() method will continue reading from the input channel until it is closed. Failure to close the input channel will cause the sorting process to hang indefinitely.
Generic API (Recommended)
The modern generic API provides type safety and improved performance:
import (
"context"
"fmt"
"math/rand"
"github.com/lanrat/extsort"
)
func main() {
// Create input channel with unsorted integers
inputChan := make(chan int, 100)
go func() {
defer close(inputChan)
for i := 0; i < 1000000; i++ {
inputChan <- rand.Int()
}
}()
// Sort using the generic API
sorter, outputChan, errChan := extsort.Ordered(inputChan, nil)
// Start sorting in background
go sorter.Sort(context.Background())
// Process sorted results
for value := range outputChan {
fmt.Println(value)
}
// Check for errors
if err := <-errChan; err != nil {
panic(err)
}
}
String Sorting
For string data, use the optimized string sorter:
import (
"context"
"fmt"
"github.com/lanrat/extsort"
)
func main() {
words := []string{"zebra", "apple", "banana", "cherry"}
inputChan := make(chan string, len(words))
for _, word := range words {
inputChan <- word
}
close(inputChan)
sorter, outputChan, errChan := extsort.Strings(inputChan, nil)
go sorter.Sort(context.Background())
fmt.Println("Sorted words:")
for word := range outputChan {
fmt.Println(word)
}
if err := <-errChan; err != nil {
panic(err)
}
}
Custom Types with Generic API
import (
"bytes"
"context"
"encoding/gob"
"fmt"
"github.com/lanrat/extsort"
)
type Person struct {
Name string
Age int
}
func personToBytes(p Person) ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(p)
return buf.Bytes(), err
}
func personFromBytes(data []byte) (Person, error) {
var p Person
buf := bytes.NewReader(data)
dec := gob.NewDecoder(buf)
err := dec.Decode(&p)
return p, err
}
func comparePersonsByAge(a, b Person) int {
// Sort by age
if a.Age != b.Age {
if a.Age < b.Age {
return -1
}
return 1
}
return 0
}
func main() {
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
inputChan := make(chan Person, len(people))
for _, person := range people {
inputChan <- person
}
close(inputChan)
sorter, outputChan, errChan := extsort.Generic(
inputChan,
personFromBytes,
personToBytes,
comparePersonsByAge,
nil,
)
go sorter.Sort(context.Background())
fmt.Println("People sorted by age:")
for person := range outputChan {
fmt.Printf("%s (age %d)\n", person.Name, person.Age)
}
if err := <-errChan; err != nil {
panic(err)
}
}
Configuration
Customize sorting behavior with the Config struct:
config := &extsort.Config{
ChunkSize: 500000, // Records per chunk (default: 1M)
NumWorkers: 4, // Parallel sorting/merging workers (default: 2)
ChanBuffSize: 10, // Channel buffer size (default: 1)
SortedChanBuffSize: 1000, // Output channel buffer (default: 1000)
TempFilesDir: "/var/tmp", // Temporary files directory (default: intelligent selection)
}
sorter, outputChan, errChan := extsort.Ordered(inputChan, config)
Temporary Directory Selection
When TempFilesDir is empty (default), the library intelligently selects temporary directories that prefer disk-backed locations over potentially memory-backed filesystems. On Linux systems where /tmp may be mounted as tmpfs (memory-backed), this helps prevent out-of-memory issues when sorting datasets larger than available RAM.
For production use with large datasets, it's recommended to explicitly set TempFilesDir to a known disk-backed directory (such as /var/tmp on Unix systems) to ensure optimal performance and avoid memory limitations.
Legacy Interface-Based API
The library maintains backward compatibility with the original interface-based API:
import (
"context"
"encoding/binary"
"fmt"
"math/rand"
"github.com/lanrat/extsort"
)
type sortInt struct {
value int64
}
func (s sortInt) ToBytes() []byte {
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, uint64(s.value))
return buf
}
func sortIntFromBytes(data []byte) extsort.SortType {
value := int64(binary.LittleEndian.Uint64(data))
return sortInt{value: value}
}
func compareSortInt(a, b extsort.SortType) bool {
return a.(sortInt).value < b.(sortInt).value
}
func main() {
inputChan := make(chan extsort.SortType, 100)
go func() {
defer close(inputChan)
for i := 0; i < 100000; i++ {
inputChan <- sortInt{value: rand.Int63()}
}
}()
sorter, outputChan, errChan := extsort.New(
inputChan,
sortIntFromBytes,
compareSortInt,
nil,
)
go sorter.Sort(context.Background())
for item := range outputChan {
fmt.Println(item.(sortInt).value)
}
if err := <-errChan; err != nil {
panic(err)
}
}
Diff Sub-Package
The diff sub-package provides functionality for comparing two sorted data streams and identifying differences. It's particularly useful for comparing large datasets efficiently.
Basic String Diff