Forum > General
As vs Cast
(1/1)
BenLaz:
Hello,
Sorry if my question is too naive, but in Delphi (and i guess in Fpc) the As operator costs a lot (in Delphi, it's sometimes more efficient to do a test with a IS and an explicit cast than a cast with AS).
The AS operator is usefull when debugging but (in my point of view) it looses a lot of its interest in release mode (as release mode sould already be debugged and so without invalid cast).
So the question is : Is there a way to convert the As cast to explicit cast (to improve speed) when not debugging ?
Best regards
taazz:
There is no difference between as and a hard cast both will raise an exception, for different reasons, if the variable does not support the class that is cast to.
marcov:
A hard cast reinterprets memory. It might access random memory and anything can happen (tm). Including exceptions, but not *guaranteed* so.
AS is basically something like
--- Code: ---function asintern.al(sss:tobject;someclass:TSomeClassType):<type of tsomeclasstype, compiler magic>
if sss IS TSomeclass then
result:=tsomeclass
else
raise exception.create
--- End code ---
If you usually capture the exception, basically by doing IS yourself you avoid the raising + catching of the exception.
But no, there are no variations on cast. Some code relies on it throwing an exception when the class isn't right.
You could maybe add an assert with IS though to get the same effect.
assert(obj IS TSomeclass); // will throw an exception if obj is not tsomeclass or derivative.
and asserts can be turned on and off.
BenLaz:
Thank very much you for your answers.
I know assertions, but i was not aware they can be disabled without code generation.
Do you know if the compiler generate code for the assert arguments (the boolean expression) because if does not do it means that if the boolean expression does something (like a property getter), this code won't be called witch means results can be differents with or without Assert support.
Anyway, i find the "assert way" a little bit heavier, hope one day there is an evolution to choose the way the as operator is generated.
Best regards
Navigation
[0] Message Index