4 ms·
In this case, perhaps mutability is the real problem. Array#filter is quite fast in JS and never mutates the array.
by STRML 10y ago
In this case, perhaps mutability is the real problem. Array#filter is quite fast in JS and never mutates the array.
- rickycook 10y agoit might be quite fast, but it's never going to be as fast as a mutable version of the same thing. there are plenty of cases where you have many (millions?) of elements and want to remove only a few. in that case, copying an array of many elements for the sake of immutability is quite wasteful *edit: i say never, but if you do cool stuff with referencing array ranges so that you don't copy, but reference the unchanged parts of the previous array then sure, but that's more of a low level feature of the language (eg erlang and clojure both do this i thiiiink?) than something you'd want to implement in a library because it can be suuuuper tricky to get right
- elmigranto 10y agoNo one does immutability with copying, that would be a joke. There is also nothing tricky about not copying full lists on append at userland lib, just more advanced data structures. Yes, it won't be as fast in modifying. But it will be a lot faster in other operations, so it's a trade off and you chose appropriately for your use case. Plus, it's a lot easier to read and understand "immutable code".
- EpicEng 10y agoLike anything, it depends. I frequently work on pieces of code cannot be optimized algorithmically and memory allocation is the bottleneck. A version which doesn't allocate a new chunk of memory will always be faster.
- mattdeboard 10y agoI'm going to assume this bottlenecked-by-mem-alloc work isn't Ruby. The rule of thumb I personally go by is that if you're working in e.g. Ruby or Python it's better to favor immutability over mutability because mem alloc will almost never be the problem. I say this having worked on a Python (pypy) product where mem alloc WAS the bottleneck in a particular area. So I know it's not always true, but almost always. Probably preaching to the choir here :)
- EpicEng 10y agoI can't disagree with you there. In this context you're probably right 99% of the time