简体   繁体   中英

Generic type class instances performance

Let's say I have a type class

trait CanMeow[T] {
    def meow(t:T):String
}

Now I have a different type class

trait IsCatEquivalent[T] {
    def makeSound(t:T):String
    def isAlive(t:T):Boolean
}

And now I want to make every CatEquivalent member of CanMeow type class. What I can do is

implicit def catEquivalentCanMeow[T](implicit ce:IsCatEquivalent[T]) = new CanMeow[T] {
    def meow(t:T) = ce.makeSound(t)
}

How does this affect performance? From the looks of it every time a method is called with implicit parameter of type CanMeow[T] a new object is constructed. Is it so? And if, is this cheap enough that it is not worth caching the instances?

Other question: is there a better way to do this? (Making one type class extend the other may not be an option, for example if they come from different libraries)

To compare the performance impact of implicit conversion and its alternatives, see this article . This question contains another microbenchmark.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM