Forked from Catfish-Man/pointless swift benchmarks
Last active
November 20, 2015 18:47
-
-
Save josephlord/33aa84a546a2d31c05ec to your computer and use it in GitHub Desktop.
Faster by removing variables - Original and optimised Swift (optimised is 30-40% faster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
private let testSize = 100_000_000 | |
private var testTime:CFAbsoluteTime = 0 | |
private var optimisedTestTime:CFAbsoluteTime = 0 | |
class Test | |
{ | |
func testing2(var x : Int) -> Int | |
{ | |
if x % 3 == 0 { | |
x += 10 | |
} | |
x++ | |
return x | |
} | |
func test() | |
{ | |
var time = NSDate.timeIntervalSinceReferenceDate(); | |
var x = 0; | |
for (var i = 0; i < testSize; i++) | |
{ | |
x = testing2(x) | |
} | |
let time2 = NSDate.timeIntervalSinceReferenceDate() - time | |
NSLog("Original: %i in %f seconds", x, time2) | |
testTime = time2 | |
} | |
} | |
Test().test() | |
final class OptimisedTest | |
{ | |
func testing2(x : Int) -> Int | |
{ | |
return x % 3 == 0 ? x + 11 : x + 1 | |
} | |
func test() | |
{ | |
let time = CFAbsoluteTimeGetCurrent() | |
var x = 0; | |
for _ in 0..<testSize { | |
x = testing2(x) | |
} | |
let time2 = CFAbsoluteTimeGetCurrent() - time | |
print("Optimised: \(x) in \(time2) seconds") | |
optimisedTestTime = time2 | |
} | |
} | |
OptimisedTest().test() | |
print((testTime / optimisedTestTime) - 1) |
Unless you built with whole module optimization, we can't devirtualize testing2 because Test may have subclasses in other files. Making Test private or final, or enabling -Owholemodule, should be sufficient to enable that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm slightly surprised that the Swift compiler wasn't eliminating test2 completely before the print out of the result was added or at least identifiying these improvements and making them equivalent.
It is notable that the changes make the code more functional (less vars, more constants).