4 ms·
From a performance point of view, is there a significant penalty associated with these "small types"? For example, kilogram as wrapper around float?
by bglazer 13y ago
From a performance point of view, is there a significant penalty associated with these "small types"?
For example, kilogram as wrapper around float?
- radicality 13y agoIt depends on the implementation. I'm not familiar with Scala, but in Haskell, using `newtype`s to achieve this creates absolutely no extra runtime overhead, only compile-time overhead when the types are checked.
- axman6 13y agoThis isn't completely true, there are issues which come up with code like newtype Foo = Foo Int map (\(Foo x) -> x) listOfFoos which should be a no-op at runtime because the representation of Foo x and x are the same, but due to the newtype, the traversal does need to occur. [1] discusses a way to avoid these problems. Basically these newtype should only ever be needed during type checking, and should really be erased after that; once you've type checked everything, then you know your program won't ever treat something which is a non Foo Int as an Int, so you can then get rid of the compile time tag and gain better optimisations. [1] http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/coercible.pdf http://research.microsoft.com/en-us/um/people/simonpj/papers...
- kasey_junk 13y agoThe way these are implemented, the short answer is yes. There will be more memory pressure on the garbage collector in Scala. The long answer is, "mmmm maybe, you should test it" because due to escape analysis, eden generation collecting speed, JIT, etc. It can get very complicated very fast. It can also be very dependent on what you mean by "significant penalty" and "performance". As an aside, Scala does allow for compile time only small types in the form of AnyVal's. They won't help in the examples in the article, but in the simpler kilogram wrapper around float it will and there will be no performance penalty as it will be elided by the compiler.
- Terr_ 13y agoOr to reuse an adage: "It's easier to optimize correct code than to correct optimized code." You can always find the slow part and change it to use raw floats/ints/etc.
- marcosdumay 13y agoAs a general rule, types are dealt with at compile time, and will only influence the optimizer leading to faster code... But as people already pointed, in practice compilers are never optimum. When it's important (that is, rarely) it's good to test, or at least read the compiler's manual.