Unicode API Call Speed

You might wonder if using Unicode when calling the Windows API would be slower or faster than using the plain "A" API. Needless to say I had the same doubt, with Unicode causing some extra memory load, I was wondering if this move really made sense for programs that don't need Unicode.

In theory, as the only real implementation of the Windows API for Vista and XP is the Unicode-based one, we should expect a faster execution, as the code will skip a string conversion during the call. So I tried with the following code, which is part of the UniApiSpeed example:

procedure TForm30.btnUserNameClick(Sender: TObject); var

I:Integer; nSize: DWORD; t1: TDateTime; str: string; pch: PChar; begi n nSize := 100; SetLength (str, nSize); pch := PChar (str); t1 := Now;

GetUserName (pch, nSize);

end;

Memo1.Lines.Add ((Sender as TButton).Caption + ' ' + FormatDateTime ('ss.zzz', t1));

17 Some more information about the WideString type and its relationship with COM is available in the section "Unicode Before Delphi 2009" at the end of this chapter. COM support still relies on the WideString type in Delphi 2009, so little has changed in that area of the product.

I compiled the same program in Delphi 7 and in Delphi 2009 and I noticed that the results were almost identical. I tried a similar loop based on the SetWindowText API call, and in this case I noticed a very odd effect. If I run the application in the debugger, it takes a 15% less time than the Delphi 7 counterpart, if I run it stand alone it becomes much slower. The problem, though is that if the program spends any time painting the caption over and over, its results will be totally modified.

These two tests are probably not very pertinent. I should have tried with many more other API calls to be able to make a definitive statement, but this proves that by moving to Unicode you can have a similar or slightly improved speed in the API calls. You don't gain a lot (at least while using non-Unicode characters), but you don't incur any extra overhead either18.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment