Hi, I’m making a vector-heavy program and I’m wondering whether I should use the mutable or immutable flavour. Are there any general guidelines on that? I understand that mutability may afford space gains, but what about performance? Do the considerations described in <https://docs.racket-lang.org/guide/performance.html|Performance §19.6> apply to general computations on vectors as well? Thanks!
That’s a variable mutation. It’s different from object mutation. So no, that section doesn’t really apply.
For vectors you should probably use mutable vectors
I think a good rule is, if you need to use vector-set!
, you need mutable vector.
But if you only vector-ref
, immutable vector is enough
See also my very relevant tweet: https://twitter.com/sorawee_p/status/1338821248982294530
Do immutable vectors have any advantage in terms of fast traversal? Say I have a program where I create and iterate/fold over lots of vectors but keep vector modification once created at a minimum.
Not really. It has an advantage in that people can reason with your program easier, because they don’t have to worry that the value will be mutated.
I see. Thank you!
If your use of the vector is such that first you do a bunch of writes, then you start reading from it and don’t do any more writes, then a good strategy is to start with a mutable vector and then copy it to an immutable one
I wrote a vector builder library to make that easier https://docs.racket-lang.org/rebellion/Vector_Builders.html\|https://docs.racket-lang.org/rebellion/Vector_Builders.html
Standard mutable vectors ought to be fast.
I can see that, say, an immutable vector with all fixnums can be represented more efficiently than a standard vector, but to my knowledge the current compiler doesn’t exploit such cases.
Have anyone measured a case, where immutable vectors are faster than mutables ones?