优化思路
- 减少递归调用开销:在深度遍历嵌套对象和数组时,递归调用会带来额外的栈空间开销以及函数调用的时间开销。可以使用迭代的方式替代递归,利用栈(在JavaScript和TypeScript中可以用数组模拟栈)来处理待遍历的节点,这样可以避免递归可能导致的栈溢出问题,尤其在处理深度嵌套结构时效果显著。
- 缓存中间结果:对于一些重复计算的部分,例如对象属性的类型判断等,可以进行缓存。比如,在遍历对象属性时,记录已经处理过的属性类型,避免重复判断。
- 尽早返回:在处理过程中,如果能提前确定某些部分不需要进一步处理(例如空对象或空数组),则尽早返回,减少不必要的计算。
代码实现
function deepOptimize<T>(input: T): T {
const stack: any[] = [input];
const result: any = Array.isArray(input)? [] : {};
const processed: WeakMap<any, any> = new WeakMap();
while (stack.length > 0) {
const current = stack.pop();
if (processed.has(current)) {
continue;
}
processed.set(current, true);
if (Array.isArray(current)) {
for (let i = 0; i < current.length; i++) {
const item = current[i];
if (typeof item === 'object' && item!== null) {
stack.push(item);
}
(result as any[])[i] = item;
}
} else if (typeof current === 'object' && current!== null) {
for (const key in current) {
if (Object.prototype.hasOwnProperty.call(current, key)) {
const value = current[key];
if (typeof value === 'object' && value!== null) {
stack.push(value);
}
(result as any)[key] = value;
}
}
} else {
result = current;
}
}
return result as T;
}