如果不在 switch case 中声明块范围,是否会导致内存泄漏? (ESLint 无案例声明)

Does it cause a memory leak if you do not declare block scope inside a switch case? (ESLint no-case-declarations)

以这段代码为例;它是一个 Redux reducer 函数:

export default (state = initialState, action) => {
    switch (action.type) {
        case EMPLOYEE_UPDATE: {                                           // <-- this {
            // action.payload === { prop: 'name', value: 'Jane' }
            const { prop, value } = action.payload
            return { ...state, [prop]: value }
        }                                                                 // <-- and this }

        default:
            return state
    }
}

我只是想解构 action.payload 以尽量减少重复,我注意到它加剧了 ES Lint 规则 (no-case-declarations)。通常,我可能会在确认规则后将其关闭。由于这个 ES Lint 定义,这个看起来更严重:

...The reason is that the lexical declaration is visible in the entire switch block but it only gets initialized when it is assigned, which will only happen if the case where it is defined is reached.

Source: https://eslint.org/docs/rules/no-case-declarations

如果我没记错的话,这是否意味着编译器将始终保持对 action.payload 的引用? -- 这意味着如果一个大循环、数据集或长 运行 计算进入那里,它可能会导致大量内存消耗,即使该案例仅在匹配 时执行,因为它不能被垃圾收集或忽略?

首先,我的解释是否正确?

我的问题的本质是 {} 在此执行 context/lexical 环境中究竟要防止什么。仅仅是内存泄漏的可能性还是有一个我没有提到的话题?

问题:

switch (true) {
  case false:
    let x = 10;
    break;
  case true:
    let x = 20; //error there's already an x declaration in scope
    break;
}

这些案例都共享相同的词法范围。所以示例运行出错。

因此,解决此问题的方法是添加块语句以引入块作用域并本地化词法声明。

switch (true) {
  case false:
    {
      let x = 10;
      break;
    }
  case true:
    {
      let x = 20;
      break;
    }
}

与内存问题无关。除了开关块内的初始化绑定(最终应该是 GC)。