What difference does it make when I use a const parameter in a procedure?
Take the following procedure for example:
procedure DoSomething(Sender: TObject; const Text: String; var Reply: String);
begin
//Text is read-only and Reply will be passed back wherever DoSomething() was called
Reply:= Text;
end;
The parameter Text: String is prefixed with const so that (as far as I know), a copy of the value is made and used – and is read-only. What I was wondering is how is does this affect the application any differently than if I didn’t put const there? Perhaps a performance trick?
Looking at the documentation states:
“Using const allows the compiler to optimize code for structured – and string-type parameters. It also provides a safeguard against unintentionally passing a parameter by reference to another routine.”
In case of a string for example the optimization means there is no additional refcounting when passing as const. Also passing as const does not mean it’s a copy. Often it internally passes as reference because the compiler ensures no write access to it.
Some very interesting articles to completly understand what’s going on under the hood:
http://delphitools.info/2010/07/28/all-hail-the-const-parameters
http://vcldeveloper.com/articles/different-function-parameter-modifiers-in-delphi
Edit:
A simple example to show that const may result in pass by reference internally: