26

I'm porting some applications from 32 to 64 bits delphi, which do a lot of text processing, and noticed an extreme change in processing speed. Did some tests with a few procedures, for example, this takes already more than 200% the time in 64bits than compiling to 32 (2000+ ms compared to ~900)

Is this normal?

function IsStrANumber(const S: AnsiString): Boolean;
var P: PAnsiChar;
begin
  Result := False;
  P := PAnsiChar(S);
  while P^ <> #0 do begin
    if not (P^ in ['0'..'9']) then Exit;
    Inc(P);
  end;
  Result := True;
end;

procedure TForm11.Button1Click(Sender: TObject);
Const x = '1234567890';
Var a,y,z: Integer;
begin
  z := GetTickCount;
  for a := 1 to 99999999 do begin
   if IsStrANumber(x) then y := 0;//StrToInt(x);
  end;
  Caption := IntToStr(GetTickCount-z);
end;
5
  • Do you see the same issue if you use StrToInt(x) ?
    – Toby Allen
    Commented Jun 29, 2012 at 10:51
  • Did you do some other tests that don't involve low-level pointer manipulation? Commented Jun 29, 2012 at 10:53
  • 2
    Yeah, doing only StrToInt in the loop: 2246ms vs 1498ms (64/32). Other than that, a large application I ported has a benchmark to test processing speed (it passes some text through a very long process with hundreds of string manipulation subroutines), the 64bit one takes almost twice the time to process.
    – hikari
    Commented Jun 29, 2012 at 11:04
  • I'd say do a few tests specifically casting your variables to either in64 or longint.
    – Pieter B
    Commented Jun 29, 2012 at 11:18
  • Int64/NativeInt still don't make a difference.
    – hikari
    Commented Jun 29, 2012 at 11:20

6 Answers 6

35

There is no current solution for this, as it is caused by the fact that the code for most of the string routines in 64 bit is compiled with PUREPASCAL defined, IOW, it is plain Delphi, no assembler, while the code for many of the important string routines in 32 bit was done by the FastCode project, and in assembler.

Currently, there are no FastCode equivalents in 64 bit, and I assume that the developer team will try to eliminate assembler anyway, especially since they are moving to more platforms.

This means that optimization of the generated code becomes more and more important. I hope that the announced move to an LLVM backend will speed up much of the code considerably, so pure Delphi code is not such a problem anymore.

So sorry, no solution, but perhaps an explanation.

Update

As of XE4, quite a few FastCode routines have replaced the unoptimized routines I talk about in the above paragraphs. They are usually still PUREPASCAL, but yet they represent a good optimization. So the situation is not as bad as it used to be. The TStringHelper and plain string routines still display some bugs and some extremely slow code in OS X (especially where conversion from Unicode to Ansi or vice versa is concerned), but the Win64 part of the RTL seems to be a lot better.

30
  • I see.. well that's sad. I put a lot of time into my projects into benchmarking and trying different approaches for every little routine to achieve better speed; this 64-bit thing was a big slap from Delphi, when I was expecting even a little faster code.
    – hikari
    Commented Jun 29, 2012 at 11:56
  • 3
    @hikari: Benchmarking is good, if it is done on the entire project and optimizing is only useful if profilng turrns out that certain routines really need a speed up. Knuth already warned about premature optimization. Commented Jun 29, 2012 at 12:44
  • 2
    Maybe we could have a new Fastcode64 project in the community.
    – Warren P
    Commented Jun 29, 2012 at 13:04
  • 1
    I have seen a few comments on the FastCode mailing list that there is a provisory 64 bit assembler version of the FastCode Pos function. I guess they will also take a look at other functions. I might even help them myself, although these people know a lot of tricks I don't know. Commented Jun 29, 2012 at 15:18
  • 1
    and here i thought the "native CPU" compiler was so superior to any other technologies out there that it should be able to create near perfectly-performing code even from the "PUREPASCAL" implementation ;) Commented Nov 9, 2012 at 10:53
6

Try to avoid any string allocation in your loop.

In your case, the stack preparation of the x64 calling convention could be involved. Did you try to make IsStrANumber declared as inline?

I guess this will make it faster.

function IsStrANumber(P: PAnsiChar): Boolean; inline;
begin
  Result := False;
  if P=nil then exit;
  while P^ <> #0 do
    if not (P^ in ['0'..'9']) then 
      Exit else
      Inc(P);
  Result := True;
end;

procedure TForm11.Button1Click(Sender: TObject);
Const x = '1234567890';
Var a,y,z: Integer;
    s: AnsiString;
begin
  z := GetTickCount;
  s := x;
  for a := 1 to 99999999 do begin
   if IsStrANumber(pointer(s)) then y := 0;//StrToInt(x);
  end;
  Caption := IntToStr(GetTickCount-z);
end;

The "pure pascal" version of the RTL is indeed the cause of slowness here...

Note that it is even worse with FPC 64 bit compiler, when compared to the 32 bit version... Sounded that the Delphi compiler is not the only one! 64 bit does not mean "faster", whatever marketing says! It is sometimes even the contrary (e.g. the JRE is known to be slower on 64 bit, and a new x32 model is to be introduced in Linux when it comes about pointer size).

3
  • Inline does give a few extra ms, but it still takes almost twice the time in 64bit. Sure 64bit doesn't mean it's gonna be automaticall faster, however.. being half as fast is a big deal, when you have to wait 10 minutes to process a large text file rather than 5, etc..
    – hikari
    Commented Jun 29, 2012 at 17:22
  • 1
    Did you try my exact version? Just adding inline is not enough. You'll have to get rid of the whole string<->ansistring conversion, and so on. Using the temporary s variable and pointer(s) should make it faster. Commented Jun 29, 2012 at 18:23
  • Yeah your code is a bit faster, though the constant used in my example was just to show the code, in my program it's all variables. Nonetheless, compiled to 64-bit is still extremelly slower, 2-3x.
    – hikari
    Commented Jun 29, 2012 at 19:03
5

The code can be written like this with good perfomance results:

function IsStrANumber(const S: AnsiString): Boolean; inline;
var
  P: PAnsiChar;
begin
  Result := False;
  P := PAnsiChar(S);
  while True do
  begin
    case PByte(P)^ of
      0: Break;
      $30..$39: Inc(P);
    else
      Exit;
    end;
  end;
  Result := True;
end;

Intel(R) Core(TM)2 CPU T5600 @ 1.83GHz

  • x32-bit : 2730 ms
  • x64-bit : 3260 ms

Intel(R) Pentium(R) D CPU 3.40GHz

  • x32-bit : 2979 ms
  • x64-bit : 1794 ms

Unwinding the above loop can result to faster execution:

function IsStrANumber(const S: AnsiString): Boolean; inline; 
type
  TStrData = packed record
    A: Byte;
    B: Byte;
    C: Byte;
    D: Byte;
    E: Byte;
    F: Byte;
    G: Byte;
    H: Byte;
  end;
  PStrData = ^TStrData;
var
  P: PStrData;
begin
  Result := False;
  P := PStrData(PAnsiChar(S));
  while True do
  begin
    case P^.A of
      0: Break;
      $30..$39:
        case P^.B of
          0: Break;
          $30..$39:
            case P^.C of
              0: Break;
              $30..$39:
                case P^.D of
                  0: Break;
                  $30..$39:
                    case P^.E of
                      0: Break;
                      $30..$39:
                        case P^.F of
                          0: Break;
                          $30..$39:
                            case P^.G of
                              0: Break;
                              $30..$39:
                                case P^.H of
                                  0: Break;
                                  $30..$39: Inc(P);
                                else
                                  Exit;
                                end;
                            else
                              Exit;
                            end;
                        else
                          Exit;
                        end;
                    else
                      Exit;
                    end;
                else
                  Exit;
                end;
            else
              Exit;
            end;
        else
          Exit;
        end;
    else
      Exit;
    end;
  end;
  Result := True;
end;

Intel(R) Core(TM)2 CPU T5600 @ 1.83GHz

  • x32-bit : 2199 ms
  • x64-bit : 1934 ms

Intel(R) Pentium(R) D CPU 3.40GHz

  • x32-bit : 1170 ms
  • x64-bit : 1279 ms

If you also apply what Arnaud Bouchez said you can make it even faster.

2
  • This one is a bit odd: removing the 0 case for more speed (and the nil check in previous): 32bit: 811 vs 656, 64bit: 1108 vs 1654. So, in 32 bit this example is slower, but in 64bit it's faster oO
    – hikari
    Commented Jun 30, 2012 at 1:12
  • Keeping the 0 check for safety: 32bit: 1607ms, 64bit 1060
    – hikari
    Commented Jun 30, 2012 at 1:16
2

The test p^ in ['0'..'9'] is slow in 64-bit.

Added an inlined function with a test for lower/upper boundary instead of the in [] test, plus a test for an empty string.

function IsStrANumber(const S: AnsiString): Boolean; inline;
var
  P: PAnsiChar;
begin
  Result := False;
  P := Pointer(S);
  if (P = nil) then
    Exit;
  while P^ <> #0 do begin
    if (P^ < '0') then Exit;
    if (P^ > '9') then Exit;
    Inc(P);
  end;
  Result := True;
end;

Benchmark results:

        x32     x64
--------------------
hikari  1420    3963
LU RD   1029    1060

In 32 bit, main speed difference is inlining and that P := PAnsiChar(S); will call an external RTL routine for a nil check before assigning the pointer value, while P := Pointer(S); just assigns the pointer.

Observing that the goal here is to test if a string is a number and then convert it, why not use the RTL TryStrToInt(), which does all in one step and handles signs,blanks as well.

Often when profiling and optimizing routines, the most important thing is to find the right approach to the problem.

4
  • Thanks for the addition. TryStrToint seems around 8 times slower than the other methods.
    – hikari
    Commented Feb 22, 2014 at 6:30
  • Topicstarter only needs to check against digits and StrToInt converts string what always will be slower. Moreover on large set of false results Try* routines are slower even more because of raising exceptions.
    – Fr0sT
    Commented Aug 10, 2015 at 7:15
  • @Fr0sT, the Try* routines are not raising exceptions. The hit/miss factor here is determing the best outcome of calling IsStrANumber plus IntToStr vs calling just TryStrToInt. The latter is about twice as fast if all are numbers and 20 % slower in worst case scenario. It is a bit unclear if the goal here is just to check if the string is a number or actually converting the string to a number. Anyway the proposed version of IsStrANumber seems to satisfy the OP.
    – LU RD
    Commented Aug 10, 2015 at 8:07
  • Yep, sure, I was confused by the "Try" prefix
    – Fr0sT
    Commented Aug 10, 2015 at 13:27
1

The benefit of 64-bit is in address space, not speed (unless your code is limited by addressable memory).

Historically, this sort of character manipulation code has always been slower on wider machines. It was true moving from the 16-bit 8088/8086 to the 32-bit 386. Putting an 8-bit char in a 64-bit register is a waste of memory bandwidth & cache.

For speed, you can avoid char variables, use pointers, use lookup tables, use bit-parallelism (manipulate 8 chars in one 64-bit word), or use the SSE/SSE2... instructions. Obviously, some of these will make your code CPUID dependent. Also, open the CPU window while debugging, and look for the compiler doing stupid things "for" you like silent string conversions (especially around calls).

You might try looking at some of the native Pascal routines in the FastCode Library. E.G. PosEx_Sha_Pas_2, while not as fast as the assembler versions, is faster than the RTL code (in 32-bits).

1
  • PosEx_Sha_Pas_2 seems actually ~60-70% slower than Pos in 64-bit (and 10x slower in 32bit).
    – hikari
    Commented Jun 30, 2012 at 15:16
1

Here are two functions. One checks only for positive numbers. The second checks for negative aswell. And is not limited to size. The second one is 4x faster than regular Val.

function IsInteger1(const S: String): Boolean; overload;
var
  E: Integer;
  Value: Integer;
begin
  Val(S, Value, E);
  Result := E = 0;
end;


function IsInteger2(const S: String): Boolean; inline; 
var
    I: Integer;
begin
    Result := False;
    I := 0;
  while True do
  begin
    case Ord(S[I+1]) of
      0: Break;
      $30..$39:
        case Ord(S[I+2]) of
          0: Break;
          $30..$39:
            case Ord(S[I+3]) of
              0: Break;
              $30..$39:
                case Ord(S[I+4]) of
                  0: Break;
                  $30..$39:
                    case Ord(S[I+5]) of
                      0: Break;
                      $30..$39:
                        case Ord(S[I+6]) of
                          0: Break;
                          $30..$39:
                            case Ord(S[I+7]) of
                              0: Break;
                              $30..$39:
                                case Ord(S[I+8]) of
                                  0: Break;
                                  $30..$39:
                                    case Ord(S[I+9]) of
                                      0: Break;
                                      $30..$39: 
                                        case Ord(S[I+10]) of
                                          0: Break;
                                          $30..$39: Inc(I, 10);
                                        else
                                          Exit;
                                        end;
                                    else
                                      Exit;
                                    end;
                                else
                                  Exit;
                                end;
                            else
                              Exit;
                            end;
                        else
                          Exit;
                        end;
                    else
                      Exit;
                    end;
                else
                  Exit;
                end;
            else
              Exit;
            end;
        else
          Exit;
        end;
    else
      Exit;
    end;
  end;
  Result := True;
end;

function IsInteger3(const S: String): Boolean; inline;
var
  I: Integer;
begin
  Result := False;
  case Ord(S[1]) of
    $2D,
    $30 .. $39:
    begin
      I := 1;
      while True do
      case Ord(S[I + 1]) of
        0:
        Break;
        $30 .. $39:
        case Ord(S[I + 2]) of
          0:
          Break;
          $30 .. $39:
          case Ord(S[I + 3]) of
            0:
            Break;
            $30 .. $39:
            case Ord(S[I + 4]) of
              0:
              Break;
              $30 .. $39:
              case Ord(S[I + 5]) of
                0:
                Break;
                $30 .. $39:
                case Ord(S[I + 6]) of
                  0:
                  Break;
                  $30 .. $39:
                  case Ord(S[I + 7]) of
                    0:
                    Break;
                    $30 .. $39:
                    case Ord(S[I + 8]) of
                      0:
                      Break;
                      $30 .. $39:
                      case Ord(S[I + 9]) of
                        0:
                        Break;
                        $30 .. $39:
                        case Ord(S[I + 10]) of
                          0:
                          Break;
                          $30 .. $39:
                          case Ord(S[I + 11]) of
                            0:
                            Break;
                            $30 .. $39:
                            case Ord(S[I + 12]) of
                              0:
                              Break;
                              $30 .. $39:
                              case Ord(S[I + 13]) of
                                0:
                                Break;
                                $30 .. $39:
                                Inc(I, 13);
                              else
                                Exit;
                              end; 
                            else
                              Exit;
                            end; 
                          else
                            Exit;
                          end; 
                        else
                          Exit;
                        end; 
                      else
                        Exit;
                      end; 
                    else
                      Exit;
                    end; 
                  else
                    Exit;
                  end; 
                else
                  Exit;
                end; 
              else
                Exit;
              end;  
            else
              Exit;
            end;  
          else
            Exit;
          end;   
        else
          Exit;
        end;    
      else
        Exit;
      end;
    end;
  else
    Exit;
  end;
  Result := True;
end;
2
  • This seems to be the fastest way so far, although it will freeze if you call it with an AnsiString. Thanks.
    – hikari
    Commented Feb 22, 2014 at 6:31
  • @hikari Try calling the IsStrANumber with S: String and this function. There is a string conversion with IsStrANumber Commented Feb 22, 2014 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.