Code-golfing is incredibly fun to do, trying to solve the given problem is one thing but the real challenge is getting your code as short as possible.
Some languages are perfect for golfing because of their short commands, sadly Delphi isn't one of them.
I'm looking for tips that are useful for golfing in Delphi.
Tips like "Use 1 letter variables" don't really count in my opinion since that is pretty obvious.
Tips I learned working with Delphi or found in other peoples answers so far are:
- Semicolon isn't always required (Example 1)
- Use
int8
orint16
as datatype rather than integer (saves 3 or 2 characters) - Combine string manipulations(Example 2)
Example 1:
Procedure Example1(i:int16);
var x:int16;
begin
for x:=0to 99do
if i=1then
inc(i)//Semicolon not allowed because of "else"
else
i:=i+3//No semicolon required
end;//Semicolon required
Example 2
function WrongExample2(myString:string):string;
const
f:string='The result of your manipulation is: %s';
begin
myString:= StringReplace(s,'x', '_', [RfReplaceAll]);
Result := Format(f,[myString])
end;
function CorrectExample2(myString:string):string;
const
f:string='The result of your manipulation is: %s';
begin
Result := Format(f,[StringReplace(s,'x', '_', [RfReplaceAll])])
end;
i:=i+3
is shorter theninc(i,3)
. \$\endgroup\$const
can automatically resolve types, in your case:string
is not required. \$\endgroup\$