Alex Rivera | Logout

Is the use of `const` dogmatic or rational?

Asked 2011-04-30T22:03:33.897
23

In Delphi you can speed up your code by passing parameters as const, e.g.

function A(const AStr: string): integer;

//or

function B(AStr: string): integer;

Suppose both functions have the same code inside, the speed difference between them is negligible and I doubt it can even be measured with a cycle-counter like:

function RDTSC: comp;
var
  TimeStamp: record case byte of
    1: (Whole: comp);
    2: (Lo, Hi: Longint);
  end;
begin
  asm
    db $0F; db $31;
    mov [TimeStamp.Lo], eax
    mov [TimeStamp.Hi], edx
  end;
  Result := TimeStamp.Whole;
end;

The reason for this is that all the const does in function A is to prevent the reference count of AStr to be incremented.
But the increment only takes one cycle of one core of my multicore CPU, so...

Why should I bother with const?

Edit
Report

2 Answers

26

Don't forget that const isn't only there to provide those tiny performance improvements.

Using const explains to anybody reading or maintaining the code that the value shouldn't be updated, and allows the compiler to catch any accidental attempts to do so.

So making your code more readable and maintainable can also make it marginally faster. What good reasons are there for not using const?

answered 2011-04-30T22:16:26.937
0

One of the most important fact that people omitted. Interlock ... instruction is very costly in Multicore CPUs of x86 instruction. Read Intel manual. The cost is when refcounter var is taken placed and it is not in cpu cache, ALL other CPUs must be stopped for instruction to carried out.

Cheers

answered 2011-05-01T02:32:06.670

Your Answer