遍历对象、数组或字符串前预存长度是否为更佳编码实践?
Great questions! Let's break this down one by one since each case has its own nuances:
1. 对象遍历:是否需要预先保存长度?
First off, plain JavaScript objects don't have a native length property (unless they're array-like, like arguments). So when you want to traverse an object's properties, you'll usually start by getting a collection of its keys/values/entries via Object.keys(obj), Object.values(obj), or Object.entries(obj)—which all return arrays.
- If your loop doesn't modify the original object (no adding/deleting properties), pre-saving the array's length is mostly a style choice. Modern JS engines optimize property lookups well, so checking
keys.lengthin the loop condition vs. a pre-storedlenvariable will have negligible performance difference. - If your loop does modify the object (e.g., adding new properties mid-loop), pre-saving the array of keys is critical. Because
Object.keys(obj)generates a snapshot of the object's properties at the time it's called, storing that array (and its length) ensures you only traverse the properties that existed when you started—avoiding unexpected iterations over new properties.
For example:
const user = { name: "Alice", age: 30 }; // Safe: Traverse only initial properties, even if we add one mid-loop const keys = Object.keys(user); const len = keys.length; for (let i = 0; i < len; i++) { const key = keys[i]; console.log(`${key}: ${user[key]}`); if (key === "name") user.email = "alice@example.com"; // New property won't be traversed }
2. 数组遍历:预存长度是不是更优实践?
This is a classic question that's evolved a lot with modern JS engines.
- Performance-wise: Older engines (pre-ES5) would re-read
arr.lengthon every loop iteration, which could add overhead for huge arrays. But today's engines (V8, SpiderMonkey, etc.) automatically cache the length if the array isn't modified during the loop. So unless you're targeting very old environments, pre-saving length won't give you a meaningful performance boost. - Safety-wise: If your loop modifies the array's length (e.g.,
push,pop,splice), pre-saving the length is essential. Without it, you might end up with an infinite loop or unintended iterations over newly added elements. - Readability-wise: If your array has a long variable name (e.g.,
userDatabaseEntries), storingconst len = userDatabaseEntries.lengthcan make the loop condition cleaner (i < lenvs.i < userDatabaseEntries.length). For short names likearr, it's totally up to your preference.
Example of the safety use case:
const numbers = [1, 2, 3]; // Risky: Infinite loop because we're pushing new elements, increasing length every iteration for (let i = 0; i < numbers.length; i++) { numbers.push(numbers[i] + 3); } // Safe: Only loop through the original 3 elements const len = numbers.length; for (let i = 0; i < len; i++) { numbers.push(numbers[i] + 3); }
3. 字符串遍历:是否适用同样的做法?
Strings have a length property, but since they're immutable in JavaScript, their length can never change during traversal.
- Performance: Just like arrays, modern engines cache
str.lengthin loop conditions, so pre-saving it won't improve speed. - Use cases: Pre-saving length here is almost entirely about readability. If your string variable is long (e.g.,
customerSupportTicketMessage),const len = customerSupportTicketMessage.lengthmakes the loop cleaner. For short strings, it's unnecessary. - Note: If you're using
for...ofto traverse strings (which handles Unicode characters like emojis correctly), you don't need to worry about length at all—this method iterates directly over each character.
Example:
const greeting = "Hello 🌍"; // Both versions perform equally well for (let i = 0; i < greeting.length; i++) { console.log(greeting[i]); } const len = greeting.length; for (let i = 0; i < len; i++) { console.log(greeting[i]); }
Quick Summary
- Objects: Pre-save the keys array (and its length) only if you modify the object during traversal; otherwise, it's a style choice.
- Arrays: Pre-save length if you modify the array's length in the loop; for performance, modern engines make it unnecessary otherwise.
- Strings: Pre-save length for readability only—immutability means length won't change, and engines optimize the loop condition.
内容的提问来源于stack exchange,提问作者RGRGRG

