程序员成长-修炼中心 「作者:陈楚城」
导航
博客文章
  • Github (opens new window)
  • 掘金 (opens new window)
组件库 (opens new window)
关于我

chamberlain

前端持续学习者
导航
博客文章
  • Github (opens new window)
  • 掘金 (opens new window)
组件库 (opens new window)
关于我
  • 写在前面
  • vue3学习总结

  • 项目相关

  • 性能优化

  • 你不知道的css

  • 常见问题总结记录

  • 数据结构与算法

  • 设计模式

  • TS & JS进阶

    • typescript
    • recursive_optimization
      • 常规递归
      • 利用循环优化后的递归
      • 利用蹦床函数优化
    • functional_programming
    • 学习笔记
  • Node

  • HTTP

  • Linux

  • 开发工具篇

  • 收藏夹

  • OS

  • Nginx

  • 项目工程化

  • 数据库

  • 计算机网络

  • 环境搭建、项目部署

  • 常用工具

  • 自动化

  • js相关

  • QA相关

  • 文章收藏

  • note
  • typescript
chamberlain
2022-03-14
目录

recursive_optimization

# 递归优化

尾递归之所以需要优化,原因是调用栈太多,造成溢出,那么只要减少调用栈,就不会溢出。怎么做可以减少调用栈呢?就是采用“循环”换掉“递归”。

# 常规递归

函数调用会在内存形成一个调用记录,称调用帧,保存调用位置和内部变量等信息。

每一次循环调用函数,外层函数就会记录内层函数的调用帧,所有调用帧形成了一个调用栈,如果调用帧太多,就会发生栈溢出。

function fn(x) {
  if( x < 0) {
    return '结束'
  }
  console.log(x)
  return fn(x-1)
}
console.log(fn(100000))
// Uncaught RangeError: Maximum call stack size exceeded
1
2
3
4
5
6
7
8
9

# 利用循环优化后的递归


function fn2(x) {
    while(true) {
        if(x < 0) {
            return '结束'
        }
        console.log(x)
        x = x-1

    }
}
console.log(fn2(100000))
1
2
3
4
5
6
7
8
9
10
11
12

# 利用蹦床函数优化

function fn3(x) {
    if(x < 0) return '结束'
    console.log(x)
    return fn3.bind(null, x-1)
}

function trampoline(f) {
    while(f && f instanceof Function) {
        f = f()
    }
    return f
}
console.log(trampoline(fn3(100000)))
1
2
3
4
5
6
7
8
9
10
11
12
13

尾调用优化 (opens new window)

更新时间: 3/15/2022, 12:28:01 AM
typescript
functional_programming

← typescript functional_programming→

最近更新
01
02
网站
06-10
03
nav
06-09
更多文章>
Theme by Vdoing | Copyright © 2019-2022 chamberlain | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式