Skip to content

Instantly share code, notes, and snippets.

@josephlord
Forked from Catfish-Man/pointless swift benchmarks
Last active November 20, 2015 18:47
Show Gist options
  • Save josephlord/33aa84a546a2d31c05ec to your computer and use it in GitHub Desktop.
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
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)
@jckarter
Copy link

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