Haskell arrays vs lists

a 夏天 提交于 2019-12-30 03:48:50

问题


I'm playing with Haskell and Project Euler's 23rd problem. After solving it with lists I went here where I saw some array work. This solution was much faster than mine. So here's the question. When should I use arrays in Haskell? Is their performance better than lists' and in which cases?


回答1:


And if you're doing much indexing as well as much updating,you can

  • use Maps (or IntMaps), O(log size) indexing and update, good enough for most uses, code easy to get right
  • or, if Maps are too slow, use mutable (unboxed) arrays (STUArray from Data.Array.ST or STVectors from the vector package; O(1) indexing and update, but the code is easier to get wrong and generally not as nice.

For specific uses, functions like accumArray give very good performance too (uses mutable arrays under the hood).




回答2:


The most obvious difference is the same as in other languages: arrays have O(1) lookup and lists have O(n). Attaching something to the head of a list (:) takes O(1); appending (++) takes O(n).

Arrays have some other potential advantages as well. You can have unboxed arrays, which means the entries are just stored contiguously in memory without having a pointer to each one (if I understand the concept correctly). This has several benefits--it takes less memory and could improve cache performance.

Modifying immutable arrays is difficult--you'd have to copy the entire array which takes O(n). If you're using mutable arrays, you can modify them in O(1) time, but you'd have to give up the advantages of having a purely functional solution.

Finally, lists are just much easier to work with if performance doesn't matter. For small amounts of data, I would always use a list.




回答3:


Arrays have O(1) indexing (this used to be part of the Haskell definition), whereas lists have O(n) indexing. On the other hand, any kind of modification of arrays is O(n) since it has to copy the array. So if you're going to do a lot of indexing but little updating, use arrays.



来源:https://stackoverflow.com/questions/8196667/haskell-arrays-vs-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!