简体   繁体   中英

F# memory management

In F# when you pass an Array in a loop (recursive function calling itself) is the Array put on the stack (adding memory consumption) each loop? How does it work with lists or referenced objects when looping them? Could you minimize memory consumption somehow, maybe by using ref (references)?

If you write tail-recursive functions, then F# will do tail-call-optimization, such that the stack does not grow in each recursive call.

If you have a function that is not tail-recursive, you can use something called continuation passing style and use the heap instead of the stack for accumulating intermediate values.

As long as your function is tail recursive you don't have to worry. This simply means the last thing your function does is call itself. Example:

let rec fact x =
    if x < 1 then 1
    else x * fact (x - 1)

This function multiply's by x after fact (x - 1) so its NOT tail recursive.

Arrays are reference types, so you're not copying or constructing arrays when you pass them as arguments. If you pass around arrays in a recursive function, you're not incurring space overhead.

For example:

let rec loop a i =
  if 0 <= i && i < Array.length a then 
    loop a (a.[i])
  else
    a.[i]

This function jumps around the array until it finds a value that is not an index of the array. Assuming tail-call optimization, it has no space-overhead, ie., it allocates nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM