Best practice: Is it more efficient to replace each element or to check and replace only what has changed?
Best practice: Is it more efficient to replace each element or to check and replace only what has changed?
This question stems from a conundrum I am facing in Javascript, though a more general scientific response would be extremely helpful.
If an object or array is being iterated over for another purpose—and it is known that only one element of interest has changed which can be acted upon for manipulation—is it best to:
Simply replace every element with new data to reflect the change
Rigorously check each element and replace only that which has changed
(In this example, heights of all bars of a graph are being adjusted—as they are relative—though only one textual piece of information is targeted for change.)
Array.from(result['data']).forEach(row => {
const bar = document.getElementById('bar-' + row['date']);
bar.style.height = 'calc(1.6rem + ' + row['percentage'] + '%)';
bar.firstChild.textContent = row['distance'];
});
Or:
Array.from(result['data']).forEach(row => {
const bar = document.getElementById('bar-' + row['date']);
bar.style.height = 'calc(1.6rem + ' + row['percentage'] + '%)';
if (bar.firstChild.textContent !== row['distance']) bar.firstChild.textContent = row['distance'];
});
I suppose this is a question that exposes my ignorance and it has made it difficult for me to research a conclusion: Is it more computationally exhaustive to replace all elements when a difference is known to exist somewhere in the set, or is it cheaper to seek out the offending individual and change only that value?
(Setting timers, i.e. console.timeEnd(), has proved inconclusive.)
Any education would be throughly appreciated. I can't get my head around it.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.