This datastructure and function declaration live in a .h file:
typedef struct CxxData {
double x, y;
double m[16];
} CxxData;
double analyze(CxxData const* data);
Here is the swift code:
struct RT {
public init() {
data = CxxData(x: 0, y: 0, m: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
data2 = CxxData(x: 0, y: 0, m: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
}
public mutating func really_fast() -> Double {
// the code for this is what I want/expect, but at the price
// of making this function be mutating, which is bad
return analyze(&self.data)
}
public func should_be_as_fast() -> Double {
// I believe that the code here is doing a memcpy.
// I would love for it not to though.
return withUnsafePointer(to: self.data2) {
return analyze($0)
}
}
var data: CxxData
let data2: CxxData
}
Test code (e.g. embed in some app or something):
var rt = RT()
print(rt.really_fast())
print(rt.should_be_as_fast())
If you make a library out of this (just make the analyze() function return some constant, it need not actually look at CxxData) and call both really_fast() and should_be_as_fast() and stop in the xcode debugger with assembly turned on, you can see where a call to memcpy (appears) to be taking place. Calling this routine a few million times and timing the results agrees with the assumption that memcpy is called in the should_be_as_fast() but not in really_fast().