std.conv.to vs. casting
monarch_dodra
monarchdodra at gmail.com
Thu Jul 4 03:08:17 PDT 2013
On Thursday, 4 July 2013 at 09:31:42 UTC, Joseph Rushton Wakeling
wrote:
> On 07/04/2013 10:14 AM, monarch_dodra wrote:
>> Casting merely changes the "observed type", whereas "to" does
>> a deep conversion.
>
> What are the speed implications of to compared to cast?
>
> I ask because I see various casts in Phobos, and wonder if
> there isn't improved
> safety in preferring instead to use to, so long as the optimal
> speed is there
> with appropriate compiler optimizations.
>
> I'm particularly concerned here because of a bug I observed
> that would have been
> caught if to had been used rather than cast:
> http://d.puremagic.com/issues/show_bug.cgi?id=10322#c4
>
> (I'm working on a fix, it's just time constraints that have
> delayed delivering it:-)
Speed implications, it mostly only means doing an "if (a >
T.max)". It also means adding code to handle a throw. Finally, it
means the function can't be marked nothrow.
I'd argue that "to" should really only be used for legitimate
cases where the runtime can create out of range values, and you
want to catch that as an exception. Speed should not be a real
issue*.
I didn't go into the details, but in your bug report, it seems
like it is more of an implementation error ? In that case, an
ERROR would be better.
*Speed wise, it is not a problem I'd say, except maybe in range
primitives, espcially empty, front and opIndex, and to a certain,
popFront. It depends on the relative cost of the operation of
course.
For example: Cycle provides RA indexing. the code is written as:
"return source[(currentIndex + inputIndex) % length];"
In this specific case, there is an overflow risk, even though RA
access should be un-bounded. However, it is not checked, as the
implications to calling to would be problematic. Placing an
assert there is better, so release does not have to pay for the
check.
More information about the Digitalmars-d-learn
mailing list