Is memory released after each iteration when matching a list?

Sorry if this is a beginner's question, but I have to be sure.

When a function is called, it can create temporary objects whose memory allocation should be released after exiting.

My question is: when a function is displayed above the list, is the memory allocated by each function call immediately or only after the entire list has been processed?

This is an example of what the code specifically does, it makes no sense, except that in each function call two objects are created (newList and newRec).

Will the memory allocated for newList and newRec be allocated after each "iteration" or will all memory be freed only after the call to List.map is exited?

This should probably be easily understood for a loop in an imperative language, but I don't know how the F # compiler deals with such cases.

type MyRecord = { AList: int list; Name: string }
let myRecord = { AList = [1..100]; Name = "SomeRecord" }
let foo (arec: MyRecord) i =
    let newList = arec.AList |> List.filter (fun x -> x >= i)
    let newRec = { arec with AList = newList }
    List.sum newRec.AList
let res = [1..100] |> List.map (foo myRecord)
+4
source share
2 answers

None. F # has automatic memory management based on garbage collection . What causes the freeing of a block of memory is not a syntax condition, but a condition of execution. A memory block is freed after it becomes inaccessible.

, . foo , newList newRec , . , newList newRec , , , , . foo:

let bar (arec: MyRecord) i =
    let newList = arec.AList |> List.filter (fun x -> x >= i)
    let newRec = { arec with AList = newList }
    newRec.AList

bar , newRec , newList , .

, . , , ¹: , , , , .

foo, foo , newRec newList, , . , ; , , . , ; ( GC , , GC , ).

, foo List.map, . , List.map.

¹ , , .

+5

.NET, F #. F # -, /, , , ,.NET ( ) . , List.map, .

, , , .NET, , . , . - .

:

[1 .. 100] |> List.map (fun _ -> [1 .. 1_000_000].Length)

100 , , .

- :

[1 .. 100] |> List.map (fun _ -> [1 .. 1_000_000])

: Exception of type 'System.OutOfMemoryException' was thrown.

, 1 . , 1 . , , List.map . .

+4

Source: https://habr.com/ru/post/1689117/


All Articles