Absolute keyword in Delphi


In Delphi, you can use the keyword absolute to force the union variable. e.g. Two variables share the same memory location, which is good to do some tricky things, for example, to convert floating point IEEE format to integer.

The following shows the usage of a fast Power 2 function.

function FasterPow2a(const p: Single): Single; inline;
var
  clipp: Single;
  i: LongWord;
  f: Single absolute i;
begin
  if (p < -126) then clipp := -126 else clipp := p;
  i := Round((1 shl 23) * (clipp + 126.94269504));
  Result := f;
end;

The variable f (type of Single) shares the same memory location with LongWord variable i. It means that changing one of the variable will affect the value of the other. However, the above approach is not recommended since the compiler will not do any optimization on it. It can be simply changed using pointer type. For example,

function FasterPow2b(const p: Single): Single; inline;
var
  clipp: Single;
  i: LongWord;
  f: PSingle;
begin
  if (p < -126) then clipp := -126 else clipp := p;
  i := Round((1 shl 23) * (clipp + 126.94269504));
  f := @i;
  Result := f^;
end;

The difference is that the above variable f is an independent pointer variable (type of ^Single). Let it point to the LongWord and retrieve the variable as Single type.
However, with GetTickCount, the above two show no major performance differences, and maybe, the first approach with absolute keyword is slightly faster.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
300 words
Last Post: Check A Date String If Weekend In Java
Next Post: Codeforces: 298B Sail

The Permanent URL is: Absolute keyword in Delphi

Leave a Reply