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

perf: improve RefStateEditor.set performance #221

Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { RefStateEditor } from '../editor'

describe('editor: RefStateEditor', () => {
const editor = new RefStateEditor()

// eslint-disable-next-line test/consistent-test-it
test.each([
// Add new key.
{ refValue: { foo: 'bar' }, newValue: { foo: 'bar', bar: 'baz' } },
// Add new key and modify origin value.
{ refValue: { foo: 'bar' }, newValue: { foo: 'barr', bar: 'baz' } },
// Modify origin value.
{ refValue: { foo: 'bar' }, newValue: { foo: 'barr' } },
// Remove key.
{ refValue: { foo: 'bar' }, newValue: {} },
// Remove key and modify origin value.
{ refValue: { foo: 'bar' }, newValue: { foo: 'barr' } },
// Remove key and add new key.
{ refValue: { foo: 'bar' }, newValue: { bar: 'baz' } },
])('$refValue can be modified to $newValue by RefStateEditor.set', ({ refValue, newValue }) => {
editor.set(refValue as any, newValue)
expect(refValue).toEqual(newValue)
})
})
11 changes: 4 additions & 7 deletions packages/devtools-kit/src/core/component/state/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,26 +88,23 @@ export class StateEditor {
}
}

class RefStateEditor {
export class RefStateEditor {
set(ref: Ref<any>, value: any): void {
if (isRef(ref)) {
ref.value = value
}
else {
// if is reactive, then it must be object
// to prevent loss reactivity, we should assign key by key
const previousKeys = Object.keys(ref)
const previousKeysSet = new Set(Object.keys(ref))
const currentKeys = Object.keys(value)
// we should check the key diffs, if previous key is the longer
// then remove the needless keys
// @TODO: performance optimization
if (previousKeys.length > currentKeys.length) {
webfansplz marked this conversation as resolved.
Show resolved Hide resolved
const diffKeys = previousKeys.filter(key => !currentKeys.includes(key))
diffKeys.forEach(key => Reflect.deleteProperty(ref, key))
}
currentKeys.forEach((key) => {
Reflect.set(ref, key, Reflect.get(value, key))
previousKeysSet.delete(key)
})
previousKeysSet.forEach(key => Reflect.deleteProperty(ref, key))
webfansplz marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
Loading