I was told more than once that Delphi handles dynamic classes better than static.Thereby using the following:
type Tsomeclass=class(TObject)
private procedure proc1;
public
someint:integer;
procedure proc2;
end;
var someclass:TSomeclass;
implementation
...
initialization
someclass:=TSomeclass.Create;
finalization
someclass.Free;
rather than
type Tsomeclass=class
private class procedure proc1;
public
class var someint:integer;
class procedure proc2;
end;
90% of the classes in the project I’m working on have and need only one instance.Do I really have to use the first way for using those classes? Is it better optimized,handled by Delphi?
Sorry,I have no arguments to backup this hypothesis,but I want an expert’s opinion.
Thanks in advance!
If you create a class that contains only class variables and class methods then you can use it without the instantiation. I.e. in your second example you could use Tsomeclass.proc2 (but not Tsomeclass.someint because this variable was not marked with the ‘class’ prefix as the Uwe pointed out).
For (unmesureably small) speed difference you can also mark your class methods as ‘static’.
There’s no “handle better” comparison in my opinion here. Delphi allows you to put ‘normal’ and ‘class’ members in the class. Former you can use only on an instantiated object and latter you can use anywhere. But that’s just two parts of the OO support in Delphi.
EDIT: To answer the question about the speed …
Let’s put together a small test program:
Delphi 2010 with enabled optimisation compiles .A/.B/.C calls into
The object is first created and its address is stored away into the ebx register.
To call tc.A, compiler prepares parameter (42 or $2A) in edx, the address of the ‘tc’ instance in the eax and calls TTestClass.A.
Almost the same happens in the tc.B case except that ebx is dereferenced.
In .A and .B case, eax contains the value of the ‘Self’ (equivalent to C++’s ‘this’). When tc.A is called, eax contains the address of the ‘tc’ instance. When tc.B is called, eax contains something else (I’m guessing it’s pointing to the type info for the TTestClass but I’m not really sure about that).
When the code calls tc.C, only eax is prepared because ‘static’ methods can’t reference the ‘Self’.
Similar situation occurs in the TTestClass.B/.C cases except that ‘Self’ is loaded from some constant location when ??address of the TTestClass typeinfo?? is stored. Anyway, eax contains the same value when B is called via the instance (tc.B) or via the class (TTestClass.B).
So you can see that static calls require one ‘mov’ less. That was the inmesurable speedup I was refering to.