[DUG] In [set] efficiency

Peter Ingham ping_delphilist at 3days.co.nz
Wed Jun 8 20:14:52 NZST 2016


(From memory & without firing up a compiler to verify) ...

Sets are implemented as bitmaps with one bit allocated to each possible 
value of the set type (hence the limitations on the number of possible 
elements in the set).

So if you have
type bytesset = [0..7];  // 8 possible values
var  a: bytesset ;
begin
   if a in [1,4] then

The set literal [1,4] ends up as a byte with the value $0A.
The test "a in [1,4]" is equivalent to "(a AND $0A) <> 0".

The generated code (for a set of this size) is an AND  followed by a 
conditional jump.  Very efficient.

It gets a little nastier when the possible values gets larger as the 
size of the set grows  (set of AnsiChar is 32 bytes; Set of Widechar 
exceeds the permissible size of a set).

The precise code generated by case varies between jump tables and linear 
comparisons.

Regards


On 8/06/2016 5:27 p.m., Steve Peacocke wrote:
> If I remember correctly, the compiler changes both to array anyway so 
> you come out with exactly the same compiled code.
>
> Perhaps someone can confirm this or tell me how wrong I am?
>
> Steve Peacocke
> +64 220 612-611
>
>
> On 8/06/2016, at 4:56 PM, Ross Levis <ross at stationplaylist.com 
> <mailto:ross at stationplaylist.com>> wrote:
>
>> I’m wondering which is more efficient to process...
>>
>> if (a=1) or (a=2) then ...
>>
>> or
>>
>> if a in [1,2] then ...
>>
>> If the answer is the first method, does it make a difference if more 
>> numbers are checked, eg. if a in [1..3,5] then
>>
>> Cheers.
>>
>> _______________________________________________
>> NZ Borland Developers Group - Delphi mailing list
>> Post: delphi at listserver.123.net.nz <mailto:delphi at listserver.123.net.nz>
>> Admin: http://delphi.org.nz/mailman/listinfo/delphi
>> Unsubscribe: send an email to delphi-request at listserver.123.net.nz 
>> <mailto:delphi-request at listserver.123.net.nz> with Subject: unsubscribe
>
>
> _______________________________________________
> NZ Borland Developers Group - Delphi mailing list
> Post: delphi at listserver.123.net.nz
> Admin: http://delphi.org.nz/mailman/listinfo/delphi
> Unsubscribe: send an email to delphi-request at listserver.123.net.nz with Subject: unsubscribe


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://listserver.123.net.nz/pipermail/delphi/attachments/20160608/032534b3/attachment-0001.html 


More information about the Delphi mailing list