As an exercise in learning Swift, I rewrote a toy C++ command line tool in Swift. After switching to an UnsafeRawBufferPointer
in a critical part of the code, the Release build of the Swift version was a little faster than the Release build of the C++ version. But the Debug build took around 700 times as long. I expect a Debug build to be somewhat slower, but by that much?
Here's the critical part of the code, a function that gets called many thousands of times. The two string parameters are always 5-letter words in plain ASCII (it's related to Wordle). By the way, if I change the loop ranges from 0..<5
to [0,1,2,3,4]
, then it runs about twice as fast in Debug, but twice as slow in Release.
func Score( trial: String, target: String ) -> Int
{
var score = 0
withUnsafeBytes(of: trial.utf8) { rawTrial in
withUnsafeBytes(of: target.utf8) { rawTarget in
for i in 0..<5
{
let trial_i = rawTrial[i];
if trial_i == rawTarget[i] // strong hit
{
score += kStrongScore
}
else // check for weak hit
{
for j in 0..<5
{
if j != i
{
let target_j = rawTarget[j];
if (trial_i == target_j) &&
(rawTrial[j] != target_j)
{
score += kWeakScore
break
}
}
}
}
}
}
}
return score
}