[erlang-questions] byte_size/1 vs variable access

Erik Søe Sørensen eriksoe@REDACTED
Wed Feb 26 14:30:53 CET 2014


As far as I recall, guards aren't handled cleverly - common parts do not
result in shared code.

Regarding GC: Variables are on the stack and are released as soon as their
lifetime is done, so any extra GC-effect caused by the heap growing into
the stack sooner would presumably be small except if the variable in
question had a lifetime across a recursive call. I guess you'd have to
measure...
Den 26/02/2014 13.42 skrev "Loïc Hoguin" <essen@REDACTED>:

> Thanks.
>
> Is there any optimization when it's done inside a function clause guard?
> For example say, 5 of my 6 clauses need to check byte_size(Bin) to decide
> what to do. I am reading some code I wrote a few days ago and I see I
> instinctively used a single clause, creating a variable to hold the size
> and then used a if inside it. Perhaps the compiler is doing something about
> it in this case?
>
> I know it doesn't matter 99% of the time, but I got one or two modules
> that deal with binaries where the smallest improvement means I can handle a
> bunch more traffic. To be honest it would be really nice if the compiler
> would automatically create a variable when it sees me use byte_size/1 more
> than once as I can then stop writing all this extra code. And I'm guessing
> it could probably do the same with length/1 and others.
>
> On 02/26/2014 12:46 PM, Björn Gustavsson wrote:
>
>> On Tue, Feb 25, 2014 at 10:56 PM, Loïc Hoguin <essen@REDACTED> wrote:
>>
>>  But considering byte_size/1 is O(1) I am wondering if perhaps that's a
>>> little pointless. Is it even worth creating a variable for this? Is
>>> perhaps
>>> the variable optimized out? Perhaps accessing a variable contents and
>>> calling byte_size/1 are equivalent operations? Or the GC that will
>>> follow is
>>> not worth what little is saved by creating a variable in the first place?
>>>
>>> If someone could shed some light on this perhaps I could stop creating
>>> variables like this and simplify my code a little more.
>>>
>>>
>> There is definitely more overhead calling a BIF than accessing a variable.
>>
>> That said, I doubt that you will be able to notice the difference in a
>> real program.
>> So I suggest that you write in the way that you find most readable.
>>
>> /Bjorn
>>
>>
> --
> Loïc Hoguin
> http://ninenines.eu
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140226/7177551d/attachment.htm>


More information about the erlang-questions mailing list