Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add experimental new memoizers: autotrack and weakmap #605

Merged
merged 9 commits into from
May 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"format": "prettier --write \"{src,test}/**/*.{js,ts}\" \"docs/**/*.md\"",
"lint": "eslint src test",
"prepack": "yarn build",
"test": "vitest run",
"test": "node --expose-gc ./node_modules/vitest/dist/cli-wrapper.js run",
"test:cov": "vitest run --coverage",
"test:typescript": "tsc --noEmit -p typescript_test/tsconfig.json"
},
Expand Down
37 changes: 37 additions & 0 deletions src/autotrackMemoize/autotrackMemoize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { createNode, updateNode } from './proxy'
import { Node } from './tracking'

import { createCache } from './autotracking'
import {
createCacheKeyComparator,
defaultEqualityCheck
} from '@internal/defaultMemoize'

export function autotrackMemoize<F extends (...args: any[]) => any>(func: F) {
// we reference arguments instead of spreading them for performance reasons

const node: Node<Record<string, unknown>> = createNode(
[] as unknown as Record<string, unknown>
)

let lastArgs: IArguments | null = null

const shallowEqual = createCacheKeyComparator(defaultEqualityCheck)

const cache = createCache(() => {
const res = func.apply(null, node.proxy as unknown as any[])
return res
})

function memoized() {
if (!shallowEqual(lastArgs, arguments)) {
updateNode(node, arguments as unknown as Record<string, unknown>)
lastArgs = arguments
}
return cache.value
}

memoized.clearCache = () => cache.clear()

return memoized as F & { clearCache: () => void }
}
159 changes: 159 additions & 0 deletions src/autotrackMemoize/autotracking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Original autotracking implementation source:
// - https://gist.github.com/pzuraq/79bf862e0f8cd9521b79c4b6eccdc4f9
// Additional references:
// - https://www.pzuraq.com/blog/how-autotracking-works
// - https://v5.chriskrycho.com/journal/autotracking-elegant-dx-via-cutting-edge-cs/
import { assert } from './utils'

// The global revision clock. Every time state changes, the clock increments.
export let $REVISION = 0

// The current dependency tracker. Whenever we compute a cache, we create a Set
// to track any dependencies that are used while computing. If no cache is
// computing, then the tracker is null.
let CURRENT_TRACKER: Set<Cell<any> | TrackingCache> | null = null

type EqualityFn = (a: any, b: any) => boolean

// Storage represents a root value in the system - the actual state of our app.
export class Cell<T> {
revision = $REVISION

_value: T
_lastValue: T
_isEqual: EqualityFn = tripleEq

constructor(initialValue: T, isEqual: EqualityFn = tripleEq) {
this._value = this._lastValue = initialValue
this._isEqual = isEqual
}

// Whenever a storage value is read, it'll add itself to the current tracker if
// one exists, entangling its state with that cache.
get value() {
CURRENT_TRACKER?.add(this)

return this._value
}

// Whenever a storage value is updated, we bump the global revision clock,
// assign the revision for this storage to the new value, _and_ we schedule a
// rerender. This is important, and it's what makes autotracking _pull_
// based. We don't actively tell the caches which depend on the storage that
// anything has happened. Instead, we recompute the caches when needed.
set value(newValue) {
if (this.value === newValue) return

this._value = newValue
this.revision = ++$REVISION
}
}

function tripleEq(a: unknown, b: unknown) {
return a === b
}

// Caches represent derived state in the system. They are ultimately functions
// that are memoized based on what state they use to produce their output,
// meaning they will only rerun IFF a storage value that could affect the output
// has changed. Otherwise, they'll return the cached value.
export class TrackingCache {
_cachedValue: any
_cachedRevision = -1
_deps: any[] = []
hits = 0

fn: () => any

constructor(fn: () => any) {
this.fn = fn
}

clear() {
this._cachedValue = undefined
this._cachedRevision = -1
this._deps = []
this.hits = 0
}

get value() {
// When getting the value for a Cache, first we check all the dependencies of
// the cache to see what their current revision is. If the current revision is
// greater than the cached revision, then something has changed.
if (this.revision > this._cachedRevision) {
const { fn } = this

// We create a new dependency tracker for this cache. As the cache runs
// its function, any Storage or Cache instances which are used while
// computing will be added to this tracker. In the end, it will be the
// full list of dependencies that this Cache depends on.
const currentTracker = new Set<Cell<any>>()
const prevTracker = CURRENT_TRACKER

CURRENT_TRACKER = currentTracker

// try {
this._cachedValue = fn()
// } finally {
CURRENT_TRACKER = prevTracker
this.hits++
this._deps = Array.from(currentTracker)

// Set the cached revision. This is the current clock count of all the
// dependencies. If any dependency changes, this number will be less
// than the new revision.
this._cachedRevision = this.revision
// }
}

// If there is a current tracker, it means another Cache is computing and
// using this one, so we add this one to the tracker.
CURRENT_TRACKER?.add(this)

// Always return the cached value.
return this._cachedValue
}

get revision() {
// The current revision is the max of all the dependencies' revisions.
return Math.max(...this._deps.map(d => d.revision), 0)
}
}

export function getValue<T>(cell: Cell<T>): T {
if (!(cell instanceof Cell)) {
console.warn('Not a valid cell! ', cell)
}

return cell.value
}

type CellValue<T extends Cell<unknown>> = T extends Cell<infer U> ? U : never

export function setValue<T extends Cell<unknown>>(
storage: T,
value: CellValue<T>
): void {
assert(
storage instanceof Cell,
'setValue must be passed a tracked store created with `createStorage`.'
)

storage.value = storage._lastValue = value
}

export function createCell<T = unknown>(
initialValue: T,
isEqual: EqualityFn = tripleEq
): Cell<T> {
return new Cell(initialValue, isEqual)
}

export function createCache<T = unknown>(fn: () => T): TrackingCache {
assert(
typeof fn === 'function',
'the first parameter to `createCache` must be a function'
)

return new TrackingCache(fn)
}
Loading