Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are generics specialized during compilation or they are just like java generics only for compile time checks?

Tags:

generics

swift

There are three ways to implement generics:

  1. Just a tool for compile time checks, but every template instance is compiled to the same byte/assembly code implementation (Java, as noted in comments "type erasure" implementation)

  2. Each template instantiation is compiled to specialized code (C++, C#)

  3. Combination of #1 and #2

Which one is implemented in Swift?

like image 803
Alfa07 Avatar asked Jun 03 '14 18:06

Alfa07


People also ask

Are generics applied at compile time or run time?

Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure. For example, List<Integer> will be converted to the non-generic type List , which ordinarily contains arbitrary objects.

Do generics exist after compilation?

Some generics stay in the compiled class -- specifically including method signatures and class definitions, for example. At runtime, no objects keep their full generic type, but even at runtime you can look up the generic definition of a class or a method.

Does generics provide compile time safety?

Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.


1 Answers

Swift starts by compiling a single implementation that does dynamic type checking, but the optimizer can then choose to clone off specialized implementations for particular types when the speed vs code size tradeoffs make sense. Ideally, this gets 90% of the speedup of always cloning, without the code size and compilation time exploding.

like image 150
Catfish_Man Avatar answered Sep 28 '22 04:09

Catfish_Man