0

I was refactoring my code today to make it more efficient and suddenly a question popped into my mind. Which is more efficient and which is the best practice that can be used in any language or framework?

Approach-1

 for(let i=0;i<testList;i++){
      let reusedVar = testList[i];
        let testData= {
            firstName: reusedVar.firstName,
            lastName: reusedVar.lastName,
            ....
       }
     this.testTableData.push(testData);
     this.dataSource = new MatTableDataSource(this.testTableData);
 }

Approach-2

 for(let i=0;i<testList;i++){
  let testData= {
       firstName: testList[i].firstName,
       lastName: testList[i].lastName,
       .....
   }
 this.testTableData.push(testData);
 this.dataSource = new MatTableDataSource(this.testTableData);
}

Which approach from above is more efficient and why?

Thanks in advance.

Akki
  • 99
  • 1
  • 3
  • 12
  • 1
    It's entirely possible that the runtime would optimize the code automatically. Write code that you find readable and maintainable. – Pointy Dec 02 '21 at 13:54
  • 2
    Implementation detail of the runtime you are using. Unlikely to make much difference. Probably optimised away by the compiler. Clear example of [premature optimization](https://stackify.com/premature-optimization-evil/). – Quentin Dec 02 '21 at 13:54
  • 3
    Obligatory https://ericlippert.com/2012/12/17/performance-rant/ – Matthew Dec 02 '21 at 13:55
  • 1
    Both are inefficient. Your code can be simplified by removing the for loop and just doing `this.firstName = testList[testList.length - 1].firstName; this.lastName = testList[testList.length - 1].lastName;` – Cid Dec 02 '21 at 13:59
  • as far as I know, neither should work since you're testing a number against an object. using let will be slower since it requires creating a variable with a scope for each run. Also you should probably be using a `for var of` loop if you want readability. – John Dec 02 '21 at 13:59

0 Answers0