3 ms·
This is basically the speed advantages of C++ applied to Swift, a more powerful language. C++ also uses vtables and compilers often inline calls to methods if t
by thegeomaster 12y ago
This is basically the speed advantages of C++ applied to Swift, a more powerful language. C++ also uses vtables and compilers often inline calls to methods if the method/type can be determined at compile time.
The argument as to why it can be faster than plain C is very weak, though. It says that if C programmers don't use the restrict keyword, equivalent Swift code can be faster. This is right, but ignores the fact that careful and competent C programmers will put restrict in all the places where performance matters. It's very hard to be faster than plain C, because it has a long, long history, and as a result, the compilers have been steadily improving for a long time. It is also less powerful allowing you to be closer to the actual assembly code that is to be generated.
But with increasingly better hardware, the speed gains of plain C are diminishing. Yes, you can be very fast, but is it worth the trouble of expressing yourself in such a low-level language?
Also, since you can't type-pun (alias) in Swift, you can't do some things that can be done using plain C, so it is unclear how it can be faster.
- PeterGriffin 12y agoIf you read carefully, it's not just the advantages of C++ applied to Swift, because Swift avoids certain weaknesses of C which C++ can't (like said aliased pointers etc.). Swift is much more strict in terms of typing than either C or C++. Pointers are safe, there's no null, etc. It's the strict typing which translates to the compiler knowing more about your program before it runs, and therefore it can do more transformations without changing intent.
- stephencanon 12y ago> Also, since you can't type-pun (alias) in Swift, you can't do some things that can be done using plain C, so it is unclear how it can be faster. Type-punning is never necessary in C; it can always be replaced with one or more calls to memcpy( ), which the compiler can elide (clang, at least, is quite good at this optimization). I don't see any reason why this approach wouldn't work with Swift.
- pcwalton 12y agoLLVM isn't as good at memcpy optimization as you might think. The MemCpyOptimizer pass isn't ordered very well in the pipeline and can't make use of the SSA infrastructure that the rest of LLVM uses. Source: I'm fighting this right now in rustc and plan to fix it by just making the frontend emit fewer memcpys.
- stephencanon 12y agoIt's been a few years since I've seen clang/llvm fail to elide a memcpy used in place of type punning (it's an idiom that I use very frequently as a library writer, and care a lot about). If you have examples of cases where llvm fails to do this optimization, please file a bug report and I will be delighted to lean on the right folks to get it fixed. You shouldn't need to work around it.