I had a theory that Char would be faster than String, but sometimes you just need to try it....
It can be improved 16x by returning a CHAR instead of String. I expect that it's got to do with the allocation of the string.
I dropped the original code into a DUnit test framework and added a test to run it in a loop 100 million times. I called it YNSLoop (S for string), then made another called YNCLoop (C for Char) which returns Char instead of String, then I made another based on David's code with the Array, and I called that YNALoop (A for Array).
Then I made an inlined version of the original, per David's suggestion. That was good, so I made an Inlined Char version as well. And hey, the inline version of the Char version is even faster.
YNSLoop: 4487 ms (Original)
YNSILoop: 1226 ms (Original, Inlined)
YNCLoop: 266 ms (Char instead of String)
YNCILoop: 124 ms (Char Inlined)
YNALoop: 4548 ms (Array)
Conclusion: If you can get away using Char instead of String, do it. Either way, Inline it if you can.
Code below:
function BooleanToYNSI(isTrue: Boolean): string; inline;
begin
if isTrue then
Result := 'Y'
else
Result := 'N';
end;
function BooleanToYNS(isTrue: Boolean): string;
begin
if isTrue then
Result := 'Y'
else
Result := 'N';
end;
function BooleanToYNC(isTrue: Boolean): Char;
begin
if isTrue then
Result := 'Y'
else
Result := 'N';
end;
function BooleanToYNCI(isTrue: Boolean): Char; inline;
begin
if isTrue then
Result := 'Y'
else
Result := 'N';
end;
function BooleanToYNArray(isTrue: Boolean): string;
const
BoolStr: array [Boolean] of string = ('N', 'Y');
begin
Result := BoolStr[isTrue];
end;
procedure TDBISAM_PERFTest.YNSLoop;
var
i : integer;
begin
for i := 1 to 100000000 do
if BooleanToYNS(True) <> 'Y' then
Fail('Failed');
end;
procedure TDBISAM_PERFTest.YNSILoop;
var
i : integer;
begin
for i := 1 to 100000000 do
if BooleanToYNSI(True) <> 'Y' then
Fail('Failed');
end;
procedure TDBISAM_PERFTest.YNCLoop;
var
i : integer;
begin
for i := 1 to 100000000 do
if BooleanToYNC(True) <> 'Y' then
Fail('Failed');
end;
procedure TDBISAM_PERFTest.YNCILoop;
var
i : integer;
begin
for i := 1 to 100000000 do
if BooleanToYNCI(True) <> 'Y' then
Fail('Failed');
end;
procedure TDBISAM_PERFTest.YNALoop;
var
i : integer;
begin
for i := 1 to 100000000 do
if BooleanToYNArray(True) <> 'Y' then
Fail('Failed');
end;