Hacker News new | ask | show | jobs
by nicky0 3508 days ago
This is just speculation, but slowness might be because this is being run as a script via /usr/bin/swift, rather than being precompiled into a binary.

Certainly I have found my own Swift scripts seem to be a lot slower than compiled programs.

EDIT: from my own test with 1000 iterations, script version 17s, compiled version (release build) 5.4s

2 comments

ah great point. I'll time it both ways and see where I'm at.
I compiled it down and did a quick profile. Looks like a lot of the time is spent on line 96, converting a Character to its ascii value.

https://dl.dropboxusercontent.com/u/13740348/Screen%20Shot%2...

That's because Character is very, very different from ASCII in Swift (a character in Swift holds an extended grapheme cluster. See https://developer.apple.com/reference/swift/character). I also doubt the way they compute its ASCII value is optimal:

  extension Character {
    var asciiValue: UInt32? {
        return  String(self)
            .unicodeScalars
            .filter{$0.isASCII}
            .first?
            .value
    }
  }
Certainly if it is optimal, but probably also if it isn't, I would change the program to not do that conversion in inner loops.
This is awesome guys. Thanks.
good stuff. tbh though, only ~3x slowdown in scripting imo is pretty damn good 8)
Isn't the "scripting" part just automatically compiling behind the scenes before running? It's not an interpreter or a VM. So the code runs just as fast as the compiled version, it's just that you pay a startup cost.
That's true between a debug build and just running it as a script I believe. But a release version will be optimized, I imagine if they compared a debug build to the scripted version they'd perform similarly.
Can confirm, Debug build runs in similar time to script.
Difference is that Release builds do whole-module optimization in Swift 3.

That allows for more aggressive code specialization and inlining and can remove more reference count updates (https://swift.org/blog/whole-module-optimizations/)

however for comparison, presented without comment: python version 0.708s
btw was this after compiled to pyc?
Not sure, I'm not seeing a .pyc file in the directory. Same every time I run it though.