Delphi constant bitwise expressions

Probably a stupid question, but this is an unforgettable curiosity for me.

I have some Delphi code that looks like this:

  const
   KeyRepeatBit = 30;

 ...
   // if bit 30 of lParam is set, mark this message as handled
   if (Msg.lParam and (1 shl KeyRepeatBit)> 0) then
     Handled: = true;
 ...

(the purpose of the code is not very important)

Does the compiler see "(1 shl KeyRepeatBit)" as something that can be computed at compile time, and so it becomes constant? If not, is it possible to get something by executing it as a number and replacing the expression with a number?

+6
optimization compiler-construction delphi
source share
5 answers

Yes, the compiler evaluates the expression at compile time and uses the result value as a constant. There is no benefit in declaring another constant with the result of the result.

EDIT: The_Fox is correct. Assignable typed constants (see the {$J+} Directive) are not considered constants, and the expression evaluates at run time in this case.

+7
source share

You can make sure that this is possible only for readability:

 const KeyRepeatBit = 30; KeyRepeatMask = 1 shl KeyRepeatBit ; 
+4
source share

It converts it to constant at compile time.

However, even if this is not the case, it will not have a noticeable effect on the performance of your application.

You can process several thousand messages per second if your application is busy. Your old Pentium I can do gazillions of shifts and and per second.

Keep your code readable and project it to find bottlenecks that you then optimize - usually by looking at the algorithm and not at a level as low as you change or not.

+3
source share

I doubt that using a number (which, incidentally, will be 1073741824) will really improve performance here. It seems that you are in some kind of context of the Windows message, and this will probably add more delay than the single, and it is lightning fast, even if the number is not optimized at compiled time (anyway, I think it is optimized) .

The only exception that I could imagine is the case when this particular piece of code is run very often, but, as I said, I think it is optimized at compile time, and therefore even in this case it will not affect everything.

+2
source share

Maybe it is offtopic to your question, but I use a case record for such things, for example:

  TlParamRecord = record case Integer of 0: ( RepeatCount: Word; ScanCode: Byte; Flags: Set of (lpfExtended, lpfReserved=4, lpfContextCode, lpfPreviousKeyState, lpfTransitionState); ); 1: (lParam: LPARAM); end; 

see article on my blog for more details

+1
source share

All Articles