[erlang-questions] byte_size/1 vs variable access
Wed Feb 26 13:42:29 CET 2014
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
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.
More information about the erlang-questions