[erlang-questions] byte_size/1 vs variable access

Loïc Hoguin <>
Wed Feb 26 14:46:34 CET 2014


On 02/26/2014 02:30 PM, Björn Gustavsson wrote:
> On Wed, Feb 26, 2014 at 1:42 PM, Loïc Hoguin <> wrote:
>> 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?
>
> No. The compiler currently does not do much optimizations of guards.

Shame.

>> 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.
>>
>
> Is any of that code open-source? I occasionally look
> through BEAM assembly code looking for things
> that the BEAM compiler could handle better. Pointers
> to real-world code that is performance critical
> are appreciated.

That particular byte_size/1 related code isn't online yet. I am 
finishing it up. I do have two very performance critical modules online, 
one that I optimized to death and then some, here:

  https://github.com/extend/cowboy/blob/master/src/cowboy_protocol.erl

It uses a single binary match context for the whole thing (as far as I 
can tell, anyway).

And one where I simply reimplemented my own supervisor here:

  https://github.com/extend/ranch/blob/master/src/ranch_conns_sup.erl

If you can make any of these faster than they currently are, then I 
believe you will make happy a big part of the Erlang community.

-- 
Loïc Hoguin
http://ninenines.eu



More information about the erlang-questions mailing list