Recent

Author Topic: As vs Cast  (Read 3318 times)

BenLaz

  • New Member
  • *
  • Posts: 38
As vs Cast
« on: July 20, 2014, 12:53:27 pm »
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

  • Hero Member
  • *****
  • Posts: 5363
Re: As vs Cast
« Reply #1 on: July 20, 2014, 01:03:52 pm »
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.
Good judgement is the result of experience … Experience is the result of bad judgement.

OS : Windows 7 64 bit
Laz: Lazarus 1.4.4 FPC 2.6.4 i386-win32-win32/win64

marcov

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 7604
Re: As vs Cast
« Reply #2 on: July 20, 2014, 01:54:28 pm »
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: [Select]
function asintern.al(sss:tobject;someclass:TSomeClassType):<type of tsomeclasstype, compiler magic>
if  sss IS TSomeclass then
  result:=tsomeclass
else
 raise exception.create

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

  • New Member
  • *
  • Posts: 38
Re: As vs Cast
« Reply #3 on: July 20, 2014, 02:33:32 pm »
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