- Learning Functional Programming in Go
- Lex Sheehan
- 224字
- 2021-07-02 23:13:42
Improved performance from the Map function
One of the greatest benefits of FP is performance.
Programs today achieve better performance largely by performing more than one operation at a time using multiple CPU cores.
This means running code in parallel, and to do that, our code must be thread-safe. Programs that have a shared mutable state are not thread-safe. These programs will be bottlenecked in one core.
FP solves this bottleneck/thread safety issue by returning new instances of variables rather than changing the original instance.
![](https://epubservercos.yuewen.com/6176FA/19470400908922906/epubprivate/OEBPS/Images/Chapter_31.jpg?sign=1739055266-Sc01yMD9iIRn1qL1zVYsQ9TF7UH5GV61-0-cf5a2bad0a2624832e05a7f8229b0a16)
Let's look at the Map function to see how we can pull this off using FP:
func (cars Collection) Map(fn MapFunc) Collection {
mappedCars := make(Collection, 0, len(cars))
for _, car := range cars {
mappedCars = append(mappedCars, fn(car))
}
return mappedCars
}
Instead of appending to the cars collection, that Map receives a new variable mappedCars. The mappedCars collection is mutated, not the original cars collection.
What we are doing, tactically, when we call Map(Upgrade()) is pushing the moment that our data changes out to the last moment--in this example, after mappedCars has been populated.
We have been programming our way around FP concepts our entire career. Part of what we do in this chapter is to identify these FP patterns and see how and why we should exploit them.