Recent

Author Topic: [CLOSED] Optimization at function TFPReaderBMP.ShiftCount  (Read 1066 times)

lagprogramming

  • Sr. Member
  • ****
  • Posts: 407
[CLOSED] Optimization at function TFPReaderBMP.ShiftCount
« on: January 09, 2024, 12:43:16 pm »
packages/fcl-image/src/fpreadbmp.pp has
Code: Pascal  [Select][+][-]
  1. function TFPReaderBMP.ShiftCount(Mask : longword) : shortint;
  2. var tmp : shortint;
  3. begin
  4.   tmp:=0;
  5.   if Mask=0 then
  6.   begin
  7.     Result:=0;
  8.     exit;
  9.   end;
  10.  
  11.   while (Mask mod 2)=0 do { rightmost bit is 0 }
  12.   begin
  13.     inc(tmp);
  14.     Mask:= Mask shr 1;
  15.   end;
  16.   tmp:=tmp-(8-popcnt(byte(Mask and $FF)));
  17.   Result:=tmp;
  18. end;

The following patch replaces "while (Mask mod 2)=0 do" with the faster "while (Mask and 1)=0 do" line.
« Last Edit: January 10, 2024, 10:29:39 am by lagprogramming »

Zvoni

  • Hero Member
  • *****
  • Posts: 3001
Re: Optimization at function TFPReaderBMP.ShiftCount
« Reply #1 on: January 09, 2024, 01:04:49 pm »
Addition:
1) Line 16+17 can be coalesced into one line
2) Why use a tmp-var in the first place?
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

RayoGlauco

  • Full Member
  • ***
  • Posts: 204
  • Beers: 1567
Re: Optimization at function TFPReaderBMP.ShiftCount
« Reply #2 on: January 09, 2024, 01:28:09 pm »
My own version may be like this (I agree Zvoni's opinion):

Code: Pascal  [Select][+][-]
  1.     function TFPReaderBMP.ShiftCount(Mask : longword) : shortint;
  2.     begin
  3.       Result:=0;
  4.       if Mask=0 then
  5.         exit;
  6.      
  7.       while (Mask and 1)=0 do { rightmost bit is 0 }
  8.       begin
  9.         inc(Result);
  10.         Mask:= Mask shr 1;
  11.       end;
  12.       Result:= Result-(8-popcnt(byte(Mask and $FF)));
  13.     end;
« Last Edit: January 09, 2024, 01:34:42 pm by RayoGlauco »
To err is human, but to really mess things up, you need a computer.

AlexTP

  • Hero Member
  • *****
  • Posts: 2577
    • UVviewsoft

 

TinyPortal © 2005-2018