Thread overview | |||||
---|---|---|---|---|---|
|
November 23, 2020 rgba.ptr[0] vs rgba[0] | ||||
---|---|---|---|---|
| ||||
Hi all, I would like to know why in the code below, rgba.ptr[0] is used instead of rgba[0] and allowing the method to be @safe float[4] rgba = 0; ref inout(float) r() inout pure @trusted { pragma(inline, true); return rgba.ptr[0]; } why not : ref inout(float) r() inout pure @safe { pragma(inline, true); return rgba[0]; } avoid an allocation maybe ? Thanks for your time. |
November 23, 2020 Re: rgba.ptr[0] vs rgba[0] | ||||
---|---|---|---|---|
| ||||
Posted in reply to visitor | On Monday, 23 November 2020 at 17:34:27 UTC, visitor wrote:
> Hi all,
>
> I would like to know why in the code below, rgba.ptr[0] is used instead of rgba[0] and allowing the method to be @safe
The .ptr[0] skips bounds checking.
Since this example is static length with a constant index it shouldn't matter anyway; the compiler can see it is obviously in bounds and skip it too.
But if there's any runtime value there's a bounds check with `foo[0]` and that can be surprisingly expensive in certain situations. So `foo.ptr[0]` skipping that can give a nice performance boost.
Just without bounds checking the code is obviously trusting the programmer... hence @trusted is required instead of safe.
|
November 23, 2020 Re: rgba.ptr[0] vs rgba[0] | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | On Monday, 23 November 2020 at 17:39:09 UTC, Adam D. Ruppe wrote:
> On Monday, 23 November 2020 at 17:34:27 UTC, visitor wrote:
>> Hi all,
>>
>> I would like to know why in the code below, rgba.ptr[0] is used instead of rgba[0] and allowing the method to be @safe
>
> The .ptr[0] skips bounds checking.
>
> Since this example is static length with a constant index it shouldn't matter anyway; the compiler can see it is obviously in bounds and skip it too.
>
> But if there's any runtime value there's a bounds check with `foo[0]` and that can be surprisingly expensive in certain situations. So `foo.ptr[0]` skipping that can give a nice performance boost.
>
> Just without bounds checking the code is obviously trusting the programmer... hence @trusted is required instead of safe.
indeed because of the the static length and constant index, it was puzzling me ...
Thanks Adam for clarification
|
Copyright © 1999-2021 by the D Language Foundation