Wednesday, June 12, 2013

Why I use if MyString <> '' and not if Length(MyString) > 0 ?

1) if MyString <> '' then
2) if Length(MyString) > 0 then

Both forms are used to test whether a string is empty. Let's see what the Delphi compiler has to say:

Create a new project and add this code to it:

procedure Proc1;
   MyString: string;
  if MyString <> '' then begin


procedure Proc2;
  MyString: string;
  if Length(MyString) > 0 then begin


Put a breakpoint in front of both lines containing a if statement and run the program. When the program hits the breakpoint open the window: View -> Debug Windows - CPU Windows -> Disassembly. (I'm using Delphi XE3 here, but recent versions has the same functionality). Then we see this:

The code for the first if statement is this:

Unit1.pas.35: if MyString <> '' then begin

005ACE55 837DFC00 cmp dword ptr [ebp-$04],$00

The code for the second if statement is this:

Unit1.pas.49: if Length(MyString) > 0 then begin

005ACEF5 8B45FC mov eax,[ebp-$04]
005ACEF8 8945F4 mov [ebp-$0c],eax
005ACEFB 837DF400 cmp dword ptr [ebp-$0c],$00
005ACEFF 740B jz $005acf0c
005ACF01 8B45F4 mov eax,[ebp-$0c]
005ACF04 83E804 sub eax,$04
005ACF07 8B00 mov eax,[eax]
005ACF09 8945F4 mov [ebp-$0c],eax
005ACF0C 837DF400 cmp dword ptr [ebp-$0c],$00

One assembly instruction for the first, and five (or nine) for the second. If MyString is empty, the jump instruction (jz) will skip part of the code.

Time measures prove that the first form is faster than the second. Using Delphi XE3 (x86), if MyString is empty, the first form is slightly faster. If MyString is not empty (even 1 char in size), the first form is much faster (100% or more).