|
| 1 | +import { |
| 2 | + Canvas, |
| 3 | + ElementEvent, |
| 4 | + Rect, |
| 5 | + Group, |
| 6 | + CustomEvent, |
| 7 | + EventTarget, |
| 8 | +} from '@antv/g'; |
| 9 | +import * as tinybench from 'tinybench'; |
| 10 | + |
| 11 | +export async function event(context: { canvas: Canvas }) { |
| 12 | + const { canvas } = context; |
| 13 | + console.log(canvas); |
| 14 | + |
| 15 | + await canvas.ready; |
| 16 | + |
| 17 | + const { width, height } = canvas.getConfig(); |
| 18 | + const root = new Group(); |
| 19 | + let count = 2e4; |
| 20 | + let rects = []; |
| 21 | + let eventTargets = []; |
| 22 | + |
| 23 | + function render() { |
| 24 | + root.destroyChildren(); |
| 25 | + rects = []; |
| 26 | + |
| 27 | + for (let i = 0; i < count; i++) { |
| 28 | + const x = Math.random() * width; |
| 29 | + const y = Math.random() * height; |
| 30 | + const size = 10 + Math.random() * 40; |
| 31 | + const speed = 1 + Math.random(); |
| 32 | + |
| 33 | + const rect = new Rect({ |
| 34 | + style: { |
| 35 | + x, |
| 36 | + y, |
| 37 | + width: size, |
| 38 | + height: size, |
| 39 | + fill: 'white', |
| 40 | + stroke: '#000', |
| 41 | + lineWidth: 1, |
| 42 | + }, |
| 43 | + }); |
| 44 | + root.appendChild(rect); |
| 45 | + rects[i] = { x, y, size, speed, el: rect }; |
| 46 | + |
| 47 | + // --- |
| 48 | + const eventTarge = new EventTarget(); |
| 49 | + eventTargets.push(eventTarge); |
| 50 | + eventTarge.addEventListener(ElementEvent.BOUNDS_CHANGED, () => { |
| 51 | + // |
| 52 | + }); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + render(); |
| 57 | + canvas.appendChild(root); |
| 58 | + |
| 59 | + // benchmark |
| 60 | + // ---------- |
| 61 | + const boundsChangedEvent = new CustomEvent(ElementEvent.BOUNDS_CHANGED); |
| 62 | + boundsChangedEvent.detail = { affectChildren: true }; |
| 63 | + |
| 64 | + const bench = new tinybench.Bench({ name: 'event benchmark', time: 1e2 }); |
| 65 | + |
| 66 | + bench.add('Iterating trigger events', async () => { |
| 67 | + root.forEach((el) => { |
| 68 | + el.dispatchEvent(boundsChangedEvent); |
| 69 | + }); |
| 70 | + }); |
| 71 | + bench.add('Iterating trigger events without propagate', async () => { |
| 72 | + root.forEach((el) => { |
| 73 | + el.dispatchEvent(boundsChangedEvent, true); |
| 74 | + }); |
| 75 | + }); |
| 76 | + bench.add('Iterating over trigger events on empty objects', async () => { |
| 77 | + eventTargets.forEach((el) => { |
| 78 | + el.dispatchEvent(boundsChangedEvent); |
| 79 | + }); |
| 80 | + }); |
| 81 | + bench.add('Batch triggering events', async () => { |
| 82 | + canvas.dispatchEvent(boundsChangedEvent, true); |
| 83 | + }); |
| 84 | + |
| 85 | + await bench.run(); |
| 86 | + |
| 87 | + console.log(bench.name); |
| 88 | + console.table(bench.table()); |
| 89 | + console.log(bench.results); |
| 90 | + console.log(bench.tasks); |
| 91 | + |
| 92 | + // ---------- |
| 93 | +} |
0 commit comments