Lenses don’t seem to have any disadvantages while having significant advantages over standard Haskell: Is there any reason I shouldn’t use lenses wherever possible? Are there performance considerations? Additionally, does template Haskell have any significant overhead?
Lenses don’t seem to have any disadvantages while having significant advantages over standard Haskell:
Share
Lenses form an alternative to using direct closures over data constructors. Lenses therefore have approximately the same caveats as using functions and data constructors directly.
Some of the cons because of this:
Every time you modify a lens, you might potentially cause a lot of objects to be (re)created. For example, if you have this data structure:
…and the lens of type
Lens A String, you will create a newA,BandCevery time you “modify” that lens. This is nothing unusual in Haskell (creating lots of objects), but the object creation is hidden behind the lens, making it hard to spot as a potential performance sink.And the pros:
data-lens-fdfor an example), and this makes it possible to avoid recreating a lot of objects most of the time, due to extensive data sharing. See for example thefocusfunction, and a similar pattern of usingwithSomethingfunctions in the Snap Web framework.Lenses are not always isomorphic to closures over data constructors, however. Here are some of the differences (taking
data-lensas the implementation here):data-lens, it’s theStorecomonad. This means that every time you create a lens, there’ll be a very small extra overhead due to that data structure being created.Template Haskell code runs at compile time, and does not affect the runtime performance of lenses whatsoever.