0

I have these 2 types of looping an array. https://codesandbox.io/s/confident-rubin-e4ms1?file=/src/App.js

export default function App() {
  const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

  const useFor = () => {
    const res = [];
    for (let i = 0; i < arr.length; i++) {
      res.push(
        <span className="indent" key={i}>
          {arr[i]}
          <br />
        </span>
      );
    }
    return res;
  };

  return (
    <div className="App">
      {arr.map((i) => (
        <span key={i}>
          {i}
          <br />
        </span>
      ))}
      <hr />
      {useFor()}
    </div>
  );
}

Which is the fastes way to loop an array in ReactJs: for(){} or map()?

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Asking
  • 3,487
  • 11
  • 51
  • 106
  • unless u r running a billion loops, I think the performance is negligible. .map makes everything more readable without all the I++ and variable[I] – Someone Special Nov 22 '20 at 10:56
  • They're about the same. Using `map` is idiomatic. – xehpuk Nov 22 '20 at 11:05
  • Just, measure it, https://stackoverflow.com/questions/111368/how-do-you-performance-test-javascript-code, should be duplicate – Dennis Vash Nov 22 '20 at 11:12
  • I think you are asking the wrong question. Maybe it should be. Why my maps are slowing the React? If that is the case: Profiling, Memo, useCallback and useMemo are your helpers. – iwaduarte Nov 22 '20 at 11:34

2 Answers2

0

It is difficult to say with certainty that one is better than the other.If you're not going to use too many loops, you don't need to worry about the performance.

If you ask me, map provides much better facilities for me. Also map is good for conciseness and readability. I think the for loop doesn't look nice.

You can read this article and go to the detail of the comparison.

ogulcan
  • 125
  • 1
  • 4
  • 13
0

Simple loop to test, may not be accurate but it gives an general idea.

A thousand loop doesn't matter, a million loop, maybe a few milliseconds difference, very negligible.

//An array size of 1,000,000
var arr = new Array(1000000).fill().map((d,i)=>++i)


let t0 = performance.now();
for ( var i = 0; i < arr.length; i++ ) {
    arr[i] = arr[i]
}
let t1 = performance.now();
console.log(`For-Loop through array a million times took ${t1 - t0} milliseconds.`);

let t2 = performance.now();
arr.map(item => item)

let t3 = performance.now();
console.log(`.Map through array a million times took ${t3 - t2} milliseconds.`);

//An array size of 1,000
arr = new Array(1000).fill().map((d,i)=>++i)


t0 = performance.now();
for ( var i = 0; i < arr.length; i++ ) {
    arr[i] = arr[i]
}
 t1 = performance.now();
console.log(`For-Loop through array a thousand times took ${t1 - t0} milliseconds.`);

t2 = performance.now();
arr.map(item => item)

t3 = performance.now();
console.log(`.Map through array a thousand times took ${t3 - t2} milliseconds.`);
Someone Special
  • 12,479
  • 7
  • 45
  • 76