Swift performance, debug build hundreds of times slower than release

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
}

Replies

the Release build of the Swift version was a little faster than the Release build of the C++ version

Would you like to share your C++ version? And maybe a test harness? I love a challenge.

For large values of 5, it's better to sort the two strings to do the weak-hit tests. For small values of 5, nested loops will be just as fast in practice.

700X for debug is a bit surprising. Maybe there is something else going on. Perhaps a Swift expert will comment.

You can go into the build settings and change the optimization settings to match the release. That most likely will be at the cost of breakpoints not working as expected and possibly not being able to access some variables.