Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using Generic and Protocol as type parameters, what are the pros and cons of implement them in a function

Since Swift allows us using both Protocol and Generic as parameter types in a function, the scenario below has come into my mind:

protocol AProtocol {
    var name: String{ get }
}

class ClassA: AProtocol {
    var name = "Allen"
}

func printNameGeneric<T: AProtocol>(param: T) {
    print(param.name)
}

func printNameProtocol(param: AProtocol) {
    print(param.name)
}

The first function uses generic as parameter type with a type constraint, and the second function uses protocol as the parameter type directly. However, these two functions can have the same effect, which is the point confusing me. So my questions are:

  1. What are the specific scenarios for each of them (or a case which can only be done by the specific one, but not another)?

  2. For the given case, both functions turn out the same result. Which one is better to implement (or the pros and cons of each of them)?

This great talk has mentioned generic specialization, which is a optimization that turn the way of function dispatching from dynamic dispatching (function with non-generic parameters) to static dispatching or inlining (function with generic parameters). Since static dispatching and inlining are less expensive in contrast with dynamic dispatching, to implement functions with generic can always provide a better performance.

@Hamish also gave great information in this post, have a look for more information.

Here is a new question came to me:

struct StructA: AProtocol {
    var a: Int
}

struct StructB: AProtocol {
    var b: Int
}

func buttonClicked(sender: UIButton) {
    var aVar: AProtocol

    if sender == self.buttonA
    {
        aVar = StructA(a: 1)
    }
    else if sender == self.buttonA
    {
        aVar = StructB(b: 2)
    }

    foo(param: aVar)
}

func foo<T: AProtocol>(param: T) {
    //do something
}
  1. If there are several types conform to a Protocol, and are pass in to a generic function in different conditions dynamically. As shown above, pressing different buttons will pass different types(StructA or StructB) of parameter into function, would the generic specialization still work in this case?
like image 216
UtopianFolk Avatar asked Dec 30 '16 12:12

UtopianFolk


People also ask

What is generic protocol?

Making a Protocol Generic. There are two ways to create a generic protocol - either by defining an abstract associatedtype or the use of Self (with a capital S). The use of Self or associatedtype is what we like to call "associated types". This is because they are only associated with the protocol they are defined in.

Can only be used as a generic constraint because it has self or associated type requirements?

Protocol 'SomeProtocol' can only be used as a generic constraint because it has Self or associated type requirements. Code that uses a protocol that relies on associated types pays the price. Such code must be written using generic types. Generic types are also placeholders.


Video Answer


1 Answers

There is actually a video from this year's WWDC about that (it was about performance of classes, structs and protocols; I don't have a link but you should be able to find it).

In your second function, where you pass a any value that conforms to that protocol, you are actually passing a container that has 24 bytes of storage for the passed value, and 16 bytes for type related information (to determine which methods to call, ergo dynamic dispatch). If the passed value is now bigger than 24 bytes in memory, the object will be allocated on the heap and the container stores a reference to that object! That is actually extremely time consuming and should certainly be avoided if possible.

In your first function, where you use a generic constraint, there is actually created another function by the compiler that explicitly performs the function's operations upon that type. (If you use this function with lots of different types, your code size may, however, increase significantly; see C++ code bloat for further reference.) However, the compiler can now statically dispatch the methods, inline the function if possible and does certainly not have to allocate any heap space. Stated in the video mentioned above, code size does not have to increase significantly as code can still be shared... so the function with generic constraint is certainly the way to go!

like image 166
borchero Avatar answered Oct 26 '22 06:10

borchero