HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

Fastest Parameter Passing in delphi 7?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
passingparameterdelphifastest

Problem

I have a function that accepts a big amount of data as a parameter (sometimes 1 megabyte) I was thinking which would be the fastest way to pass that data, dunno if I got this right, but here is what I think (functionality doesn't matter, all are the same in my app, since data is never used again after this function).

// slow since the data must be copied to another location 
// in memory and passed to myfunction
function myfunction(data: string): boolean;   

// faster since a pointer to the original data is passed to 
// the function and data is never copied
function myfunction(var data: string): boolean;   

// no idea ??!!!
function myfunction(const data: string): boolean;

Solution

Executive summary

Passing by const is the fastest for Delphi string types.

Details

function myfunction(data: string): boolean;




Slow since the data must be copied to another location in memory and passed to myfunction

That's not what happens. In fact the caller does nothing more than pass the string variable, stored as a pointer, to the function. What happens in myfunction is that the reference count to the string is incremented on entry and decremented on exit. This requires an implicit try/finally to be written into the code to ensure that the decrement happens in case of exceptions. The reference counting code and the try/finally consume time.

Note that the string contents are not copied at all because Delphi strings are optimised to use copy-on-write. You only pay the price of copying them if you modify the string.

function myfunction(var data: string): boolean;




Faster since a pointer to the original data is passed to the function and data is never copied

This is pretty much equivalent to the previous by value code above. The parameter (i.e. the pointer to the string) is passed by reference rather than value, but otherwise there are no differences.

function myfunction(const data: string): boolean;


And now we come to the winner. Since the function is not allowed to modify the contents of the string, the compiler can omit the reference counting code and the try/finally. So this is the fastest of all.

Code Snippets

function myfunction(data: string): boolean;
function myfunction(var data: string): boolean;
function myfunction(const data: string): boolean;

Context

StackExchange Code Review Q#4917, answer score: 12

Revisions (0)

No revisions yet.