An implementation of HAMT data-structure in Swift

Overview

HAMT (for Swift)

An implementation of HAMT(Hash Array Mapped Trie, Bagwell) in Swift. Eonil, May 2019.

Build Status

Getting Started

Use HAMT type. This type provides these features.

  • Hash-based key-value storage.
  • All of read/write/copy amortized O(log(n)) time up to certain number of elements (see Performance section), and O(n) at worst.
  • Full "Copy-on-Write" behavior with minimal amount of copying.

The type provides these dictionary-like interfaces.

  • Conformance to Sequence protocol.
  • Conformance to Equatable protocol.
  • isEmpty: Bool
  • count: Int
  • subscript(Key) -> Value? { get set }
  • subscript(Key, default: @autoclosure () -> Value) -> Value { get set }
  • keys: Sequence
  • values: Sequence

These features are not supported (maybe yet).

  • Index and index based look-up and iteration.
  • Any other collection protocol conformance.

Copy-on-Write Persistence

As like most Swift datastrctures, HAMT is also fully CoW compliant. This means each copy of same HAMT tree shares data as much as much possible. Regardles of how many copies you make, HAMT shares most portion of tree with all other copies.

Performance

HAMT type in this library is designed to be used as persistent datastructure.

In copy-persistent scenario under 64-bit environment, HAMT provides near constant time (O(log(n)) & max depth=10, -> O(10)) single element read/write/copy performance up to hash resolution limit ((2^6)^10 items) regardless of contained item count if hash function is well distributed. Also new copy does not take extra space unless gets mutated. Copy with single element mutation takes O(log(n)) extra time and space. On the other hand, copying Swift.Dictionary takes O(n) time and extra space.

Instead, single element read/write of HAMT is about 2x/50x times slower than ephemeral Swift.Dictionary for random 64-bit integer keys and values.

Get Performance

Note that "operation count" in above graph is accumulated number.

Here's another performance comparison with copying B-Tree. Naive Swift.Dictionary is not drawn here because read/write performance is same with ephemeral one, and copying it takes too much time and didn't finish.

CRUD Performance

For small dataset, naive copying of Swift.Dictionary works better, but as copying cost increases linearly, it is no longer efficient after 1,000 items.

Therefore, HAMT is better if you need a hash-based persistent associative array data structure that can grow more than several thousands.

B-Tree shows better write performance overall. HAMT performs better after 100K items, but it doesn't seem to be really practical numbers. And it requires keys to be Comparable. By the way, as B-Tree doesn't have hash collision, it'll show more reliable performance.

Maintenance

HAMT type is implemented using PD5Bucket64 internally. PD5Bucket64 type provides all additional properties for testing and validation. PD4 type was an implementation of hash-trie, and deprecated due to high rate of wasted memory. PD5 implements HAMT and shows nearly same performance with PD4 with far less memory consumption.

I used PD5 prefix for convenience only for internals. Public major type name is HAMT, and internal types all use PD5 prefixed. If I implement a next version of algorithm, it'll be named as PD6.

If once implementation gets stabilized, maybe I'll rename all PDx prefixes to HAMT someday.

At this point, only 64-bit platforms are considered. It should work on 32-bit platforms but less performance and have not been tested.

Caution!

If you link this library, you'll notice the performance is not good as shown in the graph. As like Károly Lőrentey clarified, it's because Swift compiler does not inline and optimize over externally linked functions. You can compile HAMT source code with your code together in same module to archive best possible performance.

Credits

Contribution

Sending contribution means implicit agreement to redistribute your contribution under "MIT License".

License

This code is licensed under "MIT License". Copyright Eonil, Hoon H.. 2019. All rights reserved.

You might also like...
Developed with use Swift language. As a third party library used SDWebImage. JSON parsing using URLSession with TMDB API. This app provide by the Core Data structure.

Capstone Project 🎯 About Developed with use Swift language. As a third party library used SDWebImage. JSON parsing using URLSession with TMDB API. Ad

Conv smart represent UICollectionView data structure more than UIKit.
Conv smart represent UICollectionView data structure more than UIKit.

Conv Conv smart represent UICollectionView data structure more than UIKit. Easy definition for UICollectionView DataSource and Delegate methods. And C

Conv smart represent UICollectionView data structure more than UIKit.
Conv smart represent UICollectionView data structure more than UIKit.

Conv Conv smart represent UICollectionView data structure more than UIKit. Easy definition for UICollectionView DataSource and Delegate methods. And C

Angle is a simple Swift library that provides Angle structure representing angles.

Angle is a simple Swift library that provides Angle structure representing angles. It handles angles using circular measure by default but is al

A simple Swift sample code to reads ISO 10303-21 exchange structure (STEP P21) file for AP242 schema.

simpleP21ReadSample A simple sample code to reads ISO 10303-21 exchange structure (STEP P21) file for AP242 schema. by Tsutomu Yoshida, Minokamo Japan

Classes-and-structures-in-swift - This source files show what is the difference between class and structure

This source files show what is the difference between class and structure You ca

IOS-Quiz-App- - A trivia quiz app built with Swift using MVC structure

Quiz App A trivia quiz app built with Swift using MVC structure. Default Quiz

A Swift library for efficient highlighting, indenting, and querying the structure of language syntax.

Neon A Swift library for efficient highlighting, indenting, and querying the structure of language syntax. It features: Minimal text invalidation Supp

QuickLookProtein is a macOS Quick Look extension to preview protein/3D structure files (PDB, SDF, CIF).
QuickLookProtein is a macOS Quick Look extension to preview protein/3D structure files (PDB, SDF, CIF).

QuickLookProtein QuickLookProtein is a macOS Quick Look extension to preview protein/3D structure files (PDB, SDF, CIF). It works in all places where

Learn how to structure your iOS App with declarative state changes using Point-Free's The Composable Architecture (TCA) library.
Learn how to structure your iOS App with declarative state changes using Point-Free's The Composable Architecture (TCA) library.

Learn how to structure your iOS App with declarative state changes using Point-Free's The Composable Architecture (TCA) library.

Profile in Tree structure developed in UIKit
Profile in Tree structure developed in UIKit

Profile-Tree Profile in Tree structure developed in UIKit Screenshot Video Profi

Setup your class structure in Xcode Interface Builder and save() in Parse Server.
Setup your class structure in Xcode Interface Builder and save() in Parse Server.

ISParseBind With ISParseBind you can save, update and query PFObjects using the power of Xcode Interface Builder resources. https://www.youtube.com/wa

CryptoExchange - A fully functional structure for Crypto Exchange app without using many third party assests
CryptoExchange - A fully functional structure for Crypto Exchange app without using many third party assests

cryptoExchange A fully functional structure for Crypto Exchange app without usin

BreakingNews - Breaking News App used the MVVM structure
BreakingNews - Breaking News App used the MVVM structure

Breaking News Use Structure:- I used the MVVM structure with use cases to cleanl

Tool to convert SVG to SwiftUI's Shape structure.
Tool to convert SVG to SwiftUI's Shape structure.

SVG to SwiftUI Converter Tool to convert SVG to SwiftUI's Shape structure. This approach is much more memory efficient than introducing a SVG library

In this project I chose MVVM architectural pattern in order to design applications structure.

SwinjectExample In this project I chose MVVM architectural pattern in order to design applications structure. Also I used "Swinject" framework for con

Profile-Tree - Profile in Tree structure developed in UIKit
Profile-Tree - Profile in Tree structure developed in UIKit

Profile-Tree Profile in Tree structure developed in UIKit Screenshot Video Profi

 API-Gateway/ Lambda-Function Structure
API-Gateway/ Lambda-Function Structure

This was an app I meant to release on the Apple App Store, can't do that now so here's the code

Easier way to represent the structure of UITableView.

Shoyu Shoyu is a library written in Swift to represent UITableView data structures. Shoyu means Soy Sauce in Japanese. Usage Create single section and

Owner
Eonil
Hobo
Eonil
Profile-Tree - Profile in Tree structure developed in UIKit

Profile-Tree Profile in Tree structure developed in UIKit Screenshot Video Profi

null 1 Oct 7, 2022
Simplex-Swift - A basic implementation of the Simplex algorithm, written in Swift

Simplex-Swift - A basic implementation of the Simplex algorithm, written in Swift

Evgeny Seliverstov 5 Dec 20, 2022
Swift implementation of the longest common subsequence (LCS) algorithm.

SwiftLCS SwitLCS provides an extension of Collection that finds the indexes of the longest common subsequence with another collection. The longest com

Tommaso Madonia 212 Dec 29, 2022
Algorithms and data structures in Swift, with explanations!

Welcome to the Swift Algorithm Club! Here you'll find implementations of popular algorithms and data structures in everyone's favorite new language Sw

raywenderlich 27.2k Dec 30, 2022
Fast sorted collections for Swift using in-memory B-trees

Fast Sorted Collections for Swift Using In-Memory B-Trees Overview Reference Documentation Optimizing Collections: The Book What Are B-Trees? Why In-M

null 1.3k Dec 20, 2022
swift-algorithm 눈물이 차올라서 고갤 들어..

swift-algorithm 눈물이 차올라서 고갤 들어.. 알고리즘 정리 Union Find Dynamic Programming 자주 사용되는 문법 1. for문 거꾸로 돌리기 0...n의 반대 for i in stride(from: n, to: 0, by: -1) {

윤예지 6 Nov 8, 2022
AssignmentChalkboard - A simple assignment made in Swift

AssignmentChalkboard This is a simple assignment that i made in Swift

Angelos Staboulis 0 Jan 29, 2022
Arena is an implementation of the generational arena data structure in Swift.

Arena This package is very much work in progress. Arena is an implementation of the generational arena data structure in Swift. An Arena is useful for

null 7 Dec 7, 2021
swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

kelvin 4 Aug 14, 2022
A Graph Data Structure in Pure Swift

SwiftGraph SwiftGraph is a pure Swift (no Cocoa) implementation of a graph data structure, appropriate for use on all platforms Swift supports (iOS, m

David Kopec 700 Dec 16, 2022