Apple’s Swift programming language has the notion of “protocol” which is similar to an interface in Java or Go. So we can define a protocol that has a single function.
public protocol Getter { func get(_ index : Int) -> Int }
We need to define at least one class that has the prescribed “get” method. For good measure, I will define two of them.
public final class Trivial1 : Getter { public func get(_ index : Int) -> Int { return 1 } }
public final class Trivial7 : Getter { public func get(_ index : Int) -> Int { return 7 } }
If you are familiar with Java, this should look very familiar.
Then we can define functions that operate on the new protocol. Let us sum 100 values:
public func sum(_ g : Getter) -> Int { var s = 0 for i in 1...100 { s += g.get(i) } return s }
Clearly, there are possible optimizations with the simple implementations I have designed. Is Swift smart enough?
Let us put it to the test:
public func sum17(_ g1 : Trivial1, _ g7 : Trivial7) -> Int { return sum(g1) + sum(g7) }
This compiles down to
mov eax, 800
That is, Swift is smart enough to figure out, at a compile time, the answer.
To be clear, this is exactly what you want to happen. Anything less would be disappointing. This is no better than C and C++.
Still, we should never take anything for granted as programmers.
What is nice, also, is that you can verify this answer with a trivial script:
wget https://raw.githubusercontent.com/lemire/SwiftDisas/master/swiftdisas.py swiftc -O prot.swift python swiftdisas.py prot sum17
Compared to Java where code disassembly requires praying for the gods under a full moon, this is really nice.
Rust version also inlines all the way to 800.
https://godbolt.org/g/2gw5Tj
That would have been my expectation, but thanks for checking!
Are you sure C would do that by default with two translation units?
Is LTO on by default?
That’s a fair point. In C and C++, you may end up with slower code.
Point is: Swift does well in this instance.