Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance 为什么List.foldBack和List.fold一样快_Performance_List_F# - Fatal编程技术网

Performance 为什么List.foldBack和List.fold一样快

Performance 为什么List.foldBack和List.fold一样快,performance,list,f#,Performance,List,F#,“F#中的列表实现为单链表,这意味着仅访问列表头部的操作是O(1),元素访问是O(n)。” 考虑到这一点,从最后一个元素到第一个元素访问元素的List.foldBack应该比List.fold慢得多。但是,我无法通过测试来确认这一点: let f acc x = acc + x List.fold f 100 [1 .. 5000000] ;; List.foldBack f [1 .. 5000000] 100;; #time > List.fold f 100 [1 .. 5000

“F#中的列表实现为单链表,这意味着仅访问列表头部的操作是O(1),元素访问是O(n)。”

考虑到这一点,从最后一个元素到第一个元素访问元素的List.foldBack应该比List.fold慢得多。但是,我无法通过测试来确认这一点:

let f acc x = acc + x
List.fold f 100 [1 .. 5000000] ;;
List.foldBack f [1 .. 5000000] 100;;

#time

> List.fold f 100 [1 .. 5000000] ;;
Real: 00:00:01.379, CPU: 00:00:01.468, GC gen0: 29, gen1: 26, gen2: 2
val it : int = 1647668740
> List.foldBack f [1 .. 5000000] 100;;
Real: 00:00:01.417, CPU: 00:00:01.500, GC gen0: 28, gen1: 25, gen2: 2
val it : int = 1647668740
> 

为什么List.foldBack与List.fold的性能相同?

如果你查看List.foldBack,你会发现它将列表转换成一个数组,然后从最后应用累加器函数对其进行迭代以获得结果。

很酷,我懒得搜索源代码,不知道它有那么容易获得。非常感谢。