r/functionalprogramming • • May 06 '24

Question Immutable data structures and efficiency: what am I missing?

Hello everyone! I've recently been playing around with functional programming languages (mostly lisp specifically), and I came to an interesting (I think) realization, and I want to know if I am right or if I'm missing something.

Data structures in imperative languages are normally stored in contiguous memory. This makes both access and modification O(1), but copying is O(n). But for non-contiguous memory such as linked lists, copying is O(1), but access of arbitrary elements (meaning elements other than the beginning or end) is O(n). Is it impossible to have an array-like data structure that can be copied AND accessed in constant time? If so, is immutable state therefore inherently inefficient whenever arbitrary element access is required (because either copying or access is O(n))?

I'm not trying to dunk on anyone, I'm actually curious. I have heard that imperative programming can always be more efficient than functional programming, with the tradeoff being ergonomics and safety. I'm wondering if this is what people are referring to when they say that.

28 Upvotes

23 comments sorted by

View all comments

Show parent comment

3

u/pianocomposer321 May 08 '24

Thanks for the in-depth response! I have heard that functional languages do a lot of compile-time optimizations, and one of the things I anticipated was that that might be the solution to this problem. Do you know how a functional compiler might go about optimizing a linked list for random access? I really like the idea of code being probably pure from the actual code, so the compiler can be free to use mutations for performance gains but still be guaranteed to be safe.