Recursive function calling in JavaScript

前端 未结 2 1987
遇见更好的自我
遇见更好的自我 2021-02-01 06:41

I know you should tread lightly when making recursive calls to functions in JavaScript because your second call could be up to 10 times slower.

Eloquent JavaScript state

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 07:19

    Function calls are just more expensive than a simple loop due to all the overhead of changing the stack and setting up a new context and so on. In order for recursion to be very efficient, a language has to support some form of tail-call elimination, which basically means transforming certain kinds of recursive functions into loops. Functional languages like OCaml, Haskell and Scheme do this, but no JavaScript implementation I'm aware of does so (it would only be marginally useful unless they all did, so maybe we have a dining philosophers problem).

提交回复
热议问题