4 ms·
I've programmed mostly-functional stuff for a while in a bunch of languages and I have been working on a large performance-intensive (massively multiplayer, VR,
by mquander 10y ago
I've programmed mostly-functional stuff for a while in a bunch of languages and I have been working on a large performance-intensive (massively multiplayer, VR, and mobile!) Unity codebase for the past year.
My conclusion is that functional programming is still a good idea to the extent that you can do it. Specifically, you should still minimize and encapsulate mutable state, and you should write pure functions when possible. However, the infrastructure doesn't exist to do functional programming efficiently in a lot of ways. Examples:
- Most of the .NET standard library functions over sequences (i.e. LINQ) incur substantial time overhead and do a lot of heap allocation. Writing and using generators, same story.
- Anonymous functions incur heap allocations and overhead which does not seem to ever be optimized out in Unity's Mono runtime.
- .NET's standard library data structures are mutable.
- Most of Unity's API and the libraries people write for it are not functional.
I don't think you would be wise to try to fight these facts and paper over everything with functional abstractions, or you will die of a thousand small performance cuts.
- hacker_9 10y agoJust a note, this is mainly an Unity problem as they use an old Mono compiler and runtime. Additionally lambdas only create garbage when you capture local variables, and the normal GC is optimised to run without you noticing collections. The latest C# also has a whole library dedicated to functional data structures [1]. Additionally the C# compiler was rewritten in a functional style (proving it's capability IMO) and is completely immutable. It made sense for their use case as they can pass the syntax tree around to other threads now without fear of it changing. [1] https://www.nuget.org/packages/System.Collections.Immutable https://www.nuget.org/packages/System.Collections.Immutable