r/AskProgramming • u/hellotanjent • Nov 08 '22
Is “x' = f(x)” a programming paradigm?
Hi, I'm the author of GateBoy (a gate-level simulation of the original Game Boy hardware) and Metron (a C++ to Verilog translation tool). One big issue I had to work around for both projects is the inability of C++ (or really, any current procedural programming language) to express atomic state change in a way that is both performant and unambiguous. For example, consider the following trivial function:
void swap_and_increment(int& a, int& b) {
int old_a = a;
a = b + 1;
b = old_a + 1;
} Because the first assignment to 'a' destroys the old value of 'a', we have to store it in 'old_a' in order for the swap to work. In contrast, we could write it like this:
void swap_and_increment(int& a, int& b) {
a' = b + 1;
b' = a + 1;
} where a' means "the new value of a", but this syntax has no equivalent in real C++. This may seem like an insignificant problem at first, but when you scale up to something the size of a Game Boy simulation which has thousands of variables that need to change simultaneously it becomes a serious design problem.
GateBoy solves this problem by instrumenting every variable in debug builds to catch "old/new" bugs - variables get marked as "old" or "new" during execution and reading a "new" value when you expect an "old" value is a runtime error. Metron takes a different tactic and does some symbolic code analysis at translation time to do essentially the same thing - it can ensure that for every possible path through the code, all reads of "old" values are actually reading old values and vice versa for "new" values.
If we generalize the problem a bit, we can say that the difficulty comes in trying to model a system where the entire state of the system represented as X needs to be transformed in to a new state X' via a pure function F without constantly making copies of old state (kills performance), requiring the author to keep track of which parts of the state are old or new at any given point (causes bugs), or relying on hardware support like transactional memory (not widely available). To put it more concisely, a program in the form "x' = f(x)" has no good representation in the software programming languages we use today.
I recently had the opportunity to discuss this issue with a bunch of grizzled old software and hardware veterans, and the approximate consensus seems to be:
"x' = f(x)" as a model for global atomic state change makes sense to both software and hardware developers, with some viewing it as "just another name for a state machine" (mostly software devs) and some as "so obvious that it doesn't need to be stated" (mostly hardware devs).
There really isn't any software-oriented language out there that allows for global atomic state change to be both performant (the compiler understands the distinction between "old" and "new" and can reorder code to avoid excessive copies or temporaries) and unambiguous (the distinction between an "old" value and a "new" value has some explicit representation in the language syntax).
So, what do we call this model? Allowing the compiler to reorder statements to preserve "oldness" and "newness" during execution seems to diverge from the "a program is a sequence of operations" model of procedural programming, and the fact that we _do_ want to modify X in place instead of constantly creating new (potentially very large) state objects makes it a poor fit for functional programming.
So, my question to the Reddit audience - Does it makes sense to call "x' = f(x)" a programming paradigm? It's certainly not a new one, but it also doesn't fit well with the paradigms we've given names to. What should we do with it?
4
u/Kaisha001 Nov 09 '22
Sounds like you're trying to re-write Verilog.
There are time when explicit state tracking is necessary, but in most cases I'd rather not and let the compiler handle it.
Also you seem to be confusing performance with syntax. Just because I write:
int b = a + 1;
Doesn't mean I've created a new variable. And if I were to write:
a = a + 1;
Doesn't mean I've destroyed the 'old' a.
All optimizing compilers use SSA under the hood anyways so variable names and/or variable re-used is primarily a programmer convenience.
If you're looking to do gate-level simulation for large systems. I'd go with a GPU-compute model. Each variable is a single entry in a HUGE 'texture/buffer'. Just 'ping-pong' the data back and forth.
OTOH if you're looking to create a new language, I'd stear away from the Verilog model.
6
u/hellotanjent Nov 09 '22
I probably posted this question in the wrong forum; I have 25+ years of experience with low-level optimization, have written various things for fun and professionally in Verilog, and am quite familiar with both SSA and GPU compute.
2
1
3
u/MegaIng Nov 09 '22
Maybe not 100% what you want, but languages with tuple packing/unpacking have relatively simple syntax for this:
(x, y) = x+1, y+1Something like this should be valid in python, nim, rust, and probably a few others as well.
2
u/hellotanjent Nov 09 '22
See comment below about swap in C# - yes, you can do it that way, but that's not the point of the question.
1
u/McPhage Nov 10 '22
No, this is parallel assignment... a number of languages have it. I'll throw Ruby into the ring as well, since that's one of my favorites. It works for any variable—generally for any number of variables at the same time—and has absolutely nothing to do with the xor trick.
1
u/hellotanjent Nov 10 '22
Still not the point of the question, sorry.
1
u/McPhage Nov 10 '22
It kinda is, though—your question was, "why don't programming languages do this?" And the answer is: a lot of them do. It may not be exactly what you're looking for, but it's close enough that there isn't a strong demand within those languages for a feature that is mostly the same as a feature that already exists and is widely used.
4
u/MegaIng Nov 09 '22
Uhm, no. Those are not comparable. One of those is using tricks specifically for ints, the other is using intended functionality of the language.
1
1
u/epicwisdom Nov 09 '22
Basically you're describing SSA:
2
u/hellotanjent Nov 09 '22
Sort of, but not really. Here's my reply to a similar comment on Hacker News -
"SSA works great for keeping track of the old/newness of local variables inside a single function, but it doesn't really help with tracking old/newness of state variables (globals, heap values, stuff on the stack that persists through multiple calls to F) across function calls.
You could in theory literally represent your program as a single giant function F that stores the entire program state as local variables and then apply SSA to that, but it would probably be a mess."1
u/simply_copacetic Nov 09 '22
If you look at the “sea of nodes” way of SSA handling, you see the global state being modeled explicitly: https://pp.ipd.kit.edu/publication.php?id=braun13cc
It is more visible in the corresponding implementation. Look for “blue edges”: https://libfirm.github.io/Introduction
You are correct though, this does not work across functions very well. There have been some ideas but the representation explodes due to tracking too many things.
(Disclaimer: I’m one of the authors)
1
u/epicwisdom Nov 09 '22
If there isn't a good way of tracking it statically (it seems like there isn't - Koka lang's concept of functional-but-in-place is close but may suffer from similar issues) then your only alternative is doing it dynamically. Without specific details on the constraints I'm not so sure there's an easier way than having two copies of the entire state, reading only from the old and writing only to the new, which is basically a pure functional representation.
1
u/Accurate_Koala_4698 Nov 09 '22
I’m not following what you mean by diverging from a sequence of operations. In the sense of the language you’re working in, the compiler is producing machine operations that accomplish what the program describes. As for the machine instructions, though, I don’t really think that’s been the procedural programming model since the creation of the optimizing compiler. That third temp variable in a HLL could actually produce an XCHG with two INCs
If you’re just talking about having to deal with the extra variable in your code, then it seems like a candidate for operator overloading
2
u/hellotanjent Nov 09 '22
Actually compiling the second version of swap_and_inc into binary code requires that the (imaginary) compiler insert the equivalent of an "old_a = a" operation as an "add a, b, 1" instruction still destroys the old value of a.
In larger programs with more complicated uses of the ' symbol , the compiler might be able to eliminate "old" copies of variables if it is allowed to reorder statements in the program - the compiler can see the complete evaluation graph of all statements in F (and any sub-functions) and emit code for them in whatever order is best for performance, even if it doesn't match the declaration order.
So, when I say that it "diverges" from procedural programming, I mean that introducing the ability to refer to "the next value of x" makes the code not necessarily do things in the order you would expect to happen from a procedural viewpoint.
1
u/Accurate_Koala_4698 Nov 09 '22 edited Nov 09 '22
I'm still not sure I completely get it, but I took a crack at comparing the output emitted by gcc and Intel. In both cases the function accomplishes the high level procedure I've written, but due to their inner workings they product different procedures for the processor to accomplish the high level task. In the same sense, yes having the syntactic sugar of the proposed prime operator means that the inner workings of the compiler determines how the procedure is actually accomplished, but I still don't see how that's different from the current state:
$ cat atomic.cpp #include <stdio.h> void swap_then_inc(int &a, int &b) ; int main () { int x = 2; int y = 10; swap_then_inc(x, y); printf("%d %d", x, y); return 0; } void swap_then_inc(int &a, int &b) { int old_a = a; a = b + 1; b = old_a + 1; }$ icx -O2 -c atomic.cpp $ objdump -d atomic.o atomic.o: file format elf64-x86-64 Disassembly of section .text: 0000000000000000 <main>: 0: 50 push %rax 1: 0f ae 5c 24 04 stmxcsr 0x4(%rsp) 6: 81 4c 24 04 40 80 00 orl $0x8040,0x4(%rsp) d: 00 e: 0f ae 54 24 04 ldmxcsr 0x4(%rsp) 13: bf 00 00 00 00 mov $0x0,%edi 18: be 0b 00 00 00 mov $0xb,%esi 1d: ba 03 00 00 00 mov $0x3,%edx 22: 31 c0 xor %eax,%eax 24: e8 00 00 00 00 call 29 <main+0x29> 29: 31 c0 xor %eax,%eax 2b: 59 pop %rcx 2c: c3 ret 2d: 0f 1f 00 nopl (%rax) 0000000000000030 <_Z13swap_then_incRiS_>: 30: 8b 07 mov (%rdi),%eax 32: 8b 0e mov (%rsi),%ecx 34: ff c1 inc %ecx 36: 89 0f mov %ecx,(%rdi) 38: ff c0 inc %eax 3a: 89 06 mov %eax,(%rsi) 3c: c3 retAnd
$ g++ -O2 -c atomic.cpp $ objdump -d atomic.o atomic.o: file format elf64-x86-64 Disassembly of section .text: 0000000000000000 <_Z13swap_then_incRiS_>: 0: 8b 07 mov (%rdi),%eax 2: 8b 0e mov (%rsi),%ecx 4: 83 c0 01 add $0x1,%eax 7: 8d 51 01 lea 0x1(%rcx),%edx a: 89 17 mov %edx,(%rdi) c: 89 06 mov %eax,(%rsi) e: c3 ret Disassembly of section .text.startup: 0000000000000000 <main>: 0: 48 83 ec 08 sub $0x8,%rsp 4: ba 03 00 00 00 mov $0x3,%edx 9: be 0b 00 00 00 mov $0xb,%esi e: 31 c0 xor %eax,%eax 10: 48 8d 3d 00 00 00 00 lea 0x0(%rip),%rdi # 17 <main+0x17> 17: e8 00 00 00 00 call 1c <main+0x1c> 1c: 31 c0 xor %eax,%eax 1e: 48 83 c4 08 add $0x8,%rsp 22: c3 retTo respond to the point about the compiler needing to add the
adddirectly: maybe. Anyone writing something more complicated than this code has very little idea of how various compilers are actually accomplishing the task with current syntax. Adding new syntax would simply pierce an open can.
1
u/Qweesdy Nov 09 '22 edited Nov 09 '22
I think I need a larger example of how it's supposed to work. If you don't mind, what would this become:
void maybe_swap_and_increment(int& a, int& b, bool condition) {
int old_a = a;
if(condition) {
a = b + 1;
b = old_a + 1;
} else {
a++;
}
}
foo(int& a, int& b) {
maybe_swap_and_increment(a, b, true);
maybe_swap_and_increment(a, b, false);
maybe_swap_and_increment(a, b, true);
maybe_swap_and_increment(a, b, false);
}?
Also, are you talking about multi-threaded/multi-CPU or "no actual atomicity needed at all"? If multiple threads can execute "swap_and_increment()" at the same time then we're most of the way towards transactional memory ( https://en.wikipedia.org/wiki/Transactional_memory ).
1
u/hellotanjent Nov 09 '22
In my imaginary C++-with-primed-variables language, there would be a "top" object (the equivalent of main in C) with an update() function that would be called repeatedly by the language runtime. So your code would look something like this:
struct Top { int a = 0; int b = 0; bool condition = true; int steps = 0; bool exit = false; void update() { if (condition) { a' = b + 1; b' = a + 1; } else { a' = a + 1; } condition' = !condition; steps' = steps + 1; if (steps' == 4) exit' = true; } }and the language runtime would do something like this internally:
int main(int argc, char** argv) { Top t; while(!t.exit) { t.update(); // assignments to primed variables actually take effect here } }1
u/Qweesdy Nov 09 '22
Thanks - I think I understand now: During a "simulation tick" all reads come from the old state (which can be considered "read-only"), and all writes go to the new state (which can be considered "write-only"); and at the end of a "simulation tick" the new state becomes old state.
This doesn't have a name that I'm aware of.
"Reminiscent of, but not the same as" several things, most mentioned already (except for https://en.wikipedia.org/wiki/Multiple_buffering ).
1
u/hellotanjent Nov 09 '22
Exactly correct. I'm writing a paper about this topic, but I still want feedback from whomever I can find to help ensure I cover all the bases.
1
u/chervilious Nov 09 '22
TBH asking this question to stack overflow seems to make more sense since you'll get more experienced answer there
1
1
u/wrosecrans Nov 09 '22
You could sorta make a scoped updated object as the "primes" to get what I think you want in C++
int a =1;
int b = 1;
{
auto a_prime = updater(a, [=](){return b+1}); // lambda captures "original" value
auto b_prime = updater(b, [=](){return a+1});
std::cout << "B: " << b << endl; // Use un-modified a and b
} // end of scope triggers "prime" destructors which finally consume the lambda result, a&b now increment swapped.
// Use modified a and b1
u/hellotanjent Nov 09 '22
Oh man, I'm pretty sure that would throw performance out the window. It certainly doesn't look pretty, but maybe the optimizer would surprise me.
1
u/therealdivs1210 Nov 09 '22
In the clojure world, we put the entire state inside an atom, and the atom can be updated by sending a pure function f that takes the old state and returns a new state.
This doesn’t require copying, since all data structures are implemented “persistently”, so they share structure between “copies”.
Most clojure programs are stateless, and the ones that do have state tend to save all of it in a single atom.
Clojure also has Software Transactional Memory in which you can have transactions made up of any number of updates such that all of them are applied or none of them are.
So you have a few options:
use persistent collections + atomic state
use STM
use an embedded db that supports atomic transactions (i think sqlite would work)
1
u/hellotanjent Nov 09 '22
I would be surprised if Clojure could keep up with the rate of state changes needed by Gate Boy due to persistent data structure overhead, but the concept is very similar.
1
u/therealdivs1210 Nov 09 '22
I think you are really underestimating modern machines and VMs.
1
u/hellotanjent Nov 09 '22
You might also be underestimating the amount of computation it takes to simulate a Game Boy at gate level, even on a modern processor. :D
Seriously though, program optimization is my career. Modern VMs are hella impressive, but in this one particular case I think C-like languages have a big advantage.
1
u/therealdivs1210 Nov 09 '22
I agree I might be missing something.
Even if you don’t use Clojure, you can use the same ideas in whatever language you’re using.
1
u/deperpebepo Nov 10 '22
but are we talking about game boy simulation here or are we talking about your idea for a programming paradigm? it seems to me that transactional memory is not too far off from what you seem to be describing.
1
u/hellotanjent Nov 10 '22
I have been using my Game Boy simulation as a test bench for translating code back and forth between the software world and the hardware world. I believe that we can create programming languages that work equally well in software and hardware, but the techniques and terminology aren't quite there yet.
I'm working on a paper and an experimental programming language to test out my ideas, but I wanted to ping Reddit and other forums to see if they had any feedback I might've missed.
1
u/deperpebepo Nov 10 '22
you might want to ask /r/programminglanguages. that’s not a particularly active subreddit but it’s geared towards people who work in PL, whereas I believe this one is much broader and includes folks learning to program etc
1
1
u/dnpetrov Nov 09 '22
1
u/hellotanjent Nov 09 '22
Don't forget Lustre and Esterel. :D
1
u/dnpetrov Nov 09 '22
Oh, I see you are a man of culture as well. Yes, "data flow" languages kinda do that
x' = f(x)thing a lot.
3
u/flebron Nov 09 '22
In a previous project we used Haskell that compiled down to Verilog to design hardware. Think along the lines of BlueSpec or Clash. Haskell would force you to spell out the new state as a function of the old state of the system. This would let us do gate-level simulations of the hardware we designed. Coupled with Haskell's penchant for using primes to mean "the new value of", stuff like x' = f x was very common.
You can also use this technique outside the context of hardware specifically, and Haskell likes it when you express mutation in this form. For example, suppose you want to compute Fibonacci efficiently. This is the standard Python loop:
a = 0
b = 1
for i in range(0, n):
a, b = b, a + bUsing the destructuring tuple stuff others have described. In C of course this becomes:
int a = 0, b = 1;
int i;
for (i = 0; i < n; ++i) {
int temp = a;
a = a + b;
b = temp;
}To implement this iteration in Haskell a classic pattern is called a catamorphism, and for lists, it goes like this:
state = (0, 1)
update i (a, b) = (a + b, a)
foldr update (0, 1) [0..6] == (13,8)This isn't using any sort of syntax sugar for destructuring of anything, update is the state update function. You can have whatever update function you want there, and this separates the state transition from the iteration logic (in Haskell called a "recursion scheme"). You can't do "two updates at once" for example, or "work with a previous-previous variable", because the application of your update is not up to update, it's controlled by foldr, and its interface (type signature here, really) prevents returning, say, two different values for part of the state, or no values for part of the state.
1
u/The_Binding_Of_Data Nov 08 '22
You can do it in C# like this:
void Swap(ref int a, ref int b)
{
val1 = val1 ^ val2 ^ (val2 = val1);
}7
u/hellotanjent Nov 09 '22
Yep, something similar works in C++ but that's not really the point of the question.
3
u/hellotanjent Nov 09 '22
Also you reminded me why I usually write my example as "swap and increment both values" - because people really like to remind me of various swap tricks. :D
2
1
u/Reawey Nov 09 '22 edited Nov 09 '22
I might have misunderstood your issue but can't you use std::swap? It would give something like that:
void swap_and_inc(int * pa, int * pb){ std::swap(pa, pb); *pa++; *pb++; }
1
1
u/ITwitchToo Nov 09 '22
Since nobody has said it yet... this sounds like double buffering to me. Lots of programs need it, a simple example is Conway's Game of Life where you need to calculate the entire new state of the game before replacing the "current" state by the "new" state.
1
u/bokmann Nov 09 '22
I think you need to investigate Clojure and the Software Transactional Memory model it has. At a first read at 5am it sounds like you’ve stumbled into similar territory pondering the mutability of most languages’ memory models.
1
u/cxzuk Nov 09 '22
Hi Hellotanjent,
Hmm interesting. So some feedback already on the implementation side of things, I wanted to reply from more of a design perspective and question in the title.
C and C++ are imperative, so by design each instruction has an implicit context from the previous instruction. It doesn't naturally express the atomic behaviour you're after. Youd have rely on the compiler or manually bundle them - bundles would be the abstraction I'd aim for personally with C/C++ if you wanted something the programmer could express.
I agree with other comments, this echos SSA in such that SSA is a naming scheme. What the differences are? Not sure. I assume a' can be assigned to multiple times?
I'm wondering if it would be more useful to have the prime operator (') be a reference relative to the current value, so a' would be the previous value.
Regardless; it's not clear to me what information this provides the programmer and the compiler
Thanks for the food for thought though M ✌️ 🤔
1
u/ImpatientProf Nov 09 '22
The functional form you describe, x'=f(x), is pretty standard in numerical algorithms, though they use subscripts to indicate which element in a series is being calculated, so it would be x_(n+1) = f(x_n). If your f(x) is arbitrarily complex, you're going to need two copies of the vector x in memory: one for the old values and one for the new values. Might as well just allocate a temporary one and switch to it once all of the accesses to the old values are finished. Maybe just allocate two copies and just alternate between them.
1
u/JadenDaJedi Nov 09 '22 edited Nov 09 '22
I’m wondering if you could express a’, a’’, a’’’, etc with something like an array named a. For example, in cases where you need only up to a’, you declare something like a[2] where a[0] means a and a[1] means a’.
Any additional metadata you need could probably be carried either within the individual entries (i.e. the entries within a become some tuple or composite type e.g. if you need time of last edit you fill a with (int, time) tuples) or within the array type (e.g. if you need an arbitrary number of n’’’…s you keep a vector and use the size to track where the latest new var is). Then at the end of a transaction you can copy the final ‘new’ var to a[0] and overwrite/delete the rest.
This at least comes with the benefit that the memory for each var can be kept contiguous. Seems a little hacky and would probably use more memory but hey, if it works…
1
u/lookmeat Nov 09 '22
A lot of explanation for a simple question.
The paradigm your proposing does have a name, and does have better ways to do it. Though it's not (AFAIK) fully supported within C++. It's transactional operations. Basically within the function you have a transaction.
So the way we do this is to define a transaction. All reads within a transaction happen with the values before the transaction happens, all writes within the transaction happen at the very end atomically, that is they either all happen or non happen. A potential solution could be:
transaction {
a = b+1; //reads original b, doesn't write to a yet
b = a+1; //reads original a, doesn't write to b yet
} // a and b get written together at this point.Some programming languages let you also access the values after the transaction happens, but the changes happen atomically. So
transaction foo {
a = b+1;
b = foo.current[a] + 1 // reads a as it's current state, that is b+1
} // a and b get written hereLanguages do allow with tuple unpacking, but it depends on the details of tuples in the language. Generally this is because (a, b) = foo(), bar() runs foo and bar simultaneously, and then updates a and b simultaneously, and you are guaranteed that the update happens after the run, so the above code is identical to a,b = (b+1, a+1) and you use the original values of a and b to generate the new values and then update them.
Technically speaking, in languages where updating an individual value is not guaranteed, you can have a non-atomic write. So say that we have an expression a, b, c = b, c, a, the above would translate to (using your syntax) 'a=b;'b=c;'c=a but if setting the new value of 'b failed (say because it's a property and setting it calls a function that can fail) the failure would leave your data in an invalid, partial state. Threading can also be a problem. But you can always strengthen the requirement to always, strictly, run the update atomically/transactionally, and therefore you can only read all variables in their original state, or all variables in their new state. Basically strengthen the semantics from simultaneous to transactional.
1
u/nthcxd Nov 09 '22
Your description of old/new bug reminds me of Burton Smith’s HEP and how it implemented mutual exclusion with full/empty bits.
https://en.wikipedia.org/wiki/Burton_Smith
https://en.wikipedia.org/wiki/Heterogeneous_Element_Processor
The HEP implemented a type of mutual exclusion in which all registers and locations in data memory had associated "empty" and "full" states. Reading from a location set the state to "empty," while writing to it set the state to "full." A programmer could allow processes to halt after trying to read from an empty location or write to a full location, enforcing critical sections.
—
What you are describing is data race freedom. With Gateboy debug build you are making data races runtime exceptions. With Metron data trace freedom is achieved at compile-time via some sort of type-checking, that means, I’m assuming, all successfully compiled binaries are data race free in all possible execution paths.
X’=f(x) as a programming model is one that has a language construct that allows programmers to express arbitrary size of atomic state changes, i.e. transactional memory. It’s a language where transaction exists like “synchronized” keyword in Java.
As you pointed out, and as in software(-only) transactional memory, all before and after states are preserved until the transaction commits. Such copies exist as independent allocations leading to obvious and infamous slowdown of software transactional memory. With hardware support, for (hopefully) vast majority of small transactions, the copies of register file and caches handle the before/after copies until commit, putting hard restrictions on how many variables are involved in the transactions. When it’s too big, it falls back to software transactional memory. Transactions abort when conflicts are detected, i.e. data races, i.e. reading new when expecting old value.
In my opinion, what you are describing as x’=f(x) as a programming model is in fact transactional memory (with language/compiler/runtime support). What you seek is an atomic lexical block with that pure function F as its body, i.e. atomic blocks https://en.cppreference.com/w/cpp/language/transactional_memory, with HEP-style per-memory-location synchronization primitive.
1
u/DemolishunReddit Nov 19 '22
What if you had 3 arrays. An array for current state, and array for new state, and an array of pointers. During each "scan" the current state would be used to compute the new state. While a pointer would be updated from pointing to the current value to the new value. When the time comes for rectifying state. A pointer comparison could be made and if it differs the new state is stored in the current state. The pointer is also updated to point to the current state. I am making the assumption this is to simulate hardware state. Is this a form of paging?
I honestly don't know if this is a new paradigm or not. But it sounds like an interesting problem to solve.
0
Nov 09 '22
[deleted]
1
u/hellotanjent Nov 09 '22
A loop that wrote to only local variables would work as in C++ or any other procedural language.
A loop that wrote to persistent program state (global variables, objects in the heap) would be subject to additional rules (or possibly just marked syntactically invalid) to ensure that the program always has a single unambiguous value for X' after the top-level function has completed.
8
u/Nathanfenner Nov 09 '22
You didn't use the terminology, but what you're describing essentially sounds like a persistent data structure; it "persists" after "modification" because you always return copies instead of modifying in-place. They tend to require a lot more allocation, but by using tree structures instead of large, flat arrays, you can avoid copying large amounts of data. But the need to allocate memory and have indirection does make them a lot slower than their non-persistent counterparts. So, specifically, you often require O(log n) additional allocations per write and O(log n) pointer indirections per read. So this scales okay-ish for very large inputs, but with a massive constant overhead since indirections are so much slower than dealing directly with contiguous arrays.
However, there's a recent research paper called Perceus: Garbage Free Reference Counting with Reuse which is effectively designed to optimize this kind of code; it has been implemented in Koka an experimental functional language from Microsoft Research and also in Roc a very new pure functional programming language intended for app development. Essentially, it allows the programmer to write pure functional code which appears to be copying its input, but a combination of ahead-of-time static analysis and runtime dynamic refcount checks will convert these into mutations whenever possible.
They describe this paradigm as "functional, but in-place": you write code as though you're copying, but the compiler emits in-place mutation. So you can reason around your code as though it's purely functional, but its performance characteristics are much closer to plain imperative code.
In practice, for realistic code, Perceus can apparently achieve performance very close to in-place mutation, because the static analysis is "easy" in the cases where it's most helpful, and whenever the static analysis fails, there's a dynamic analysis (check the refcount); and whenever the dynamic analysis fails (performing a copy) you get a new unique object which allows the optimization to kick in. So as long as you're willing to put up with the (low-ish) overhead of reference counting (e.g. you're not bound by hard constraints on latency etc. that are effectively only handled by C/Ada/Fortran/C++/Rust/...) you can use Perceus to make persistent data structures fast.