Improving scale management performances with memoization? #1026
-
Hi everyone 👋 I'm actually working on a visualization based on audio data from Audio Web API : const getAudioData = () => {
const dataBuffer = new Uint8Array(BUFFER_LENGTH)
audioAnalyzer.getByteTimeDomainData(dataBuffer)
if (dataBuffer.some((v) => v > 0)) {
setAudioData((d) => [...d, dataBuffer])
}
audioReqId.current = requestAnimationFrame(getAudioData)
} So I get an array of Uint8Arrays, which come quite big after a while... So I'm having performance issues 😞 I wanted to improve my code, in particular my scale management: // Scales
const angleScale = scaleLinear({
domain: [0, BUFFER_LENGTH],
range: [0, Math.PI * 2]
})
const radiusScale = scalePower({
domain: [0, 255],
range: [0, VIZ_DIAMETER / 2],
exponent: 2
})
// Accessors
const angle = (_, i) => angleScale(i)
const radius = (d) => radiusScale(d)
// Scale update
useEffect(() => {
if (!audioData.length) return
updateScale(radiusScale, {
domain: [min(audioData[audioData.length - 1]), 255]
})
}, [audioData, radiusScale]) But I'm quite lost with this I tried this but it doesn't seem to be efficient: // Accessors
const angle = useMemo(() => (_, i) => angleScale(i), [angleScale])
const radius = useMemo(() => (d) => radiusScale(d), [radiusScale])
// Scale update
const updateRadiusScale = useCallback((data) => updateScale(radiusScale, {
domain: [min(data[data.length - 1]), 255]
}), [radiusScale])
useEffect(() => {
if (!audioData.length) return
updateRadiusScale(audioData)
}, [audioData, updateRadiusScale]) I'm getting started in this, so any help would be great, I'll be very happy to learn from you! Thx in advance |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @soykje 👋 thanks for checking out It's a bit hard to follow your question without a complete example. Generally using const radiusScale = useMemo(() =>
scalePower({
domain: [0, 255],
range: [0, VIZ_DIAMETER / 2],
exponent: 2
}),
[],
); Based on that it doesn't actually look like your scale Another note is that Hope that helps, let me know if you have any follow up questions! |
Beta Was this translation helpful? Give feedback.
Hey @soykje 👋 thanks for checking out
visx
.It's a bit hard to follow your question without a complete example. Generally using
useMemo
for scale creation is recommended, so something likeBased on that it doesn't actually look like your scale
range
ordomain
actually ever need to change based on the data (since there are no dependencies to the data)? In that case it would only be created once / wouldn't need to be updated.Another note is that
updateScale
actually returns a copy of thescale
, and because you're not updating whatradiusScale
is pointing t…