AngularJS 1.6中ng-repeat的track by仍具意义吗?是否为性能优化最佳实践?
Great question—let's break this down clearly for AngularJS 1.6 specifically.
Is track by still practically useful in AngularJS 1.6?
Absolutely. AngularJS 1.6 didn't alter the core tracking logic of ng-repeat, so track by still serves two critical, practical purposes:
Reuse DOM elements when data references shift
By default,ng-repeattracks items by their object reference. If you refresh your array with new objects that have identical content but different references (like fetching updated data from an API), Angular will destroy all existing DOM elements and rebuild them from scratch. Usingtrack bywith a unique identifier (such as an item ID) tells Angular to match items by that value instead of reference, allowing it to reuse existing DOM elements and only update their content.Example:
<!-- Default behavior: Destroys and rebuilds all <li> when items are refreshed --> <li ng-repeat="item in items">{{item.name}}</li> <!-- With track by: Reuses <li> elements where item.id matches --> <li ng-repeat="item in items track by item.id">{{item.name}}</li>Handle arrays with duplicate values
Out of the box,ng-repeatthrows an error if your array contains duplicate primitive values (like[1, 1, 2]). Usingtrack by $indexlets you bypass this restriction by tracking items based on their position in the array.Example:
<!-- Fixes duplicate value errors --> <li ng-repeat="num in [1, 1, 2] track by $index">{{num}}</li>
Is using track by a good performance practice?
It depends on your use case, but when applied thoughtfully, it absolutely qualifies as a solid performance optimization:
- When it shines: If you're working with large datasets, or your array updates frequently (e.g., real-time data feeds, paginated results),
track bycuts down on unnecessary DOM manipulation. DOM operations are resource-heavy, so reusing elements instead of destroying and rebuilding them can noticeably boost rendering speed and smoothness. - When it's less critical: For small, rarely updated arrays, the performance gain from
track byis negligible. It won't cause harm to use it, but it's not a mandatory addition here. - A key warning: Avoid using
track by $indexfor arrays where item order might change (like sorted lists). Since$indexis tied to position, reordering the array will make Angular update the content of existing DOM elements instead of reordering them—this can lead to unexpected issues like broken event bindings or component state mismatches. Always prioritize a stable, unique identifier (likeitem.id) when possible.
Final Takeaway
track by remains a valuable tool in AngularJS 1.6. It’s a reliable performance tweak for large or frequently updated datasets, and it solves specific edge cases like duplicate values. Just be sure to pick the right tracking key for your scenario to avoid unintended bugs.
内容的提问来源于stack exchange,提问作者prznov

