开发者

Compare bit sets efficiently

开发者 https://www.devze.com 2022-12-20 09:23 出处:网络
I want to store permissions in a bit set to compare them efficiently in Java. A 1 would mean p开发者_高级运维ermission granted and 0 permission denied. If the authorization is performed the required p

I want to store permissions in a bit set to compare them efficiently in Java. A 1 would mean p开发者_高级运维ermission granted and 0 permission denied. If the authorization is performed the required permissions would be compared to the permission set.

My idea is to use AND and compare the result with the requested permissions.

Example:

     0010 1101 Granted Permissions
AND  0000 0101 Requested Permissions
=    0000 0101 Result

if (Result == Requested Permissions)
    allow
else
    deny

Could that be done more efficient or simple?


I'll focus on the "simple" part, because I don't think that this operation will be a performance bottleneck in any serious application.

You can use a BitSet which has all the necessary operations.

A more OO-approach and much easier to understand and read would be to represent your permissions with an enum and to use a EnumSet. For enums with only a few values it will be about as performant as the BitSet, because it'll use a very similar implementation.


If you are using Java 5 or later, I recommend using Enum(s) and an EnumSet instead. It is much easier to handle and AFAIK performs equally well.


Your approach is perfectly fine and will work as expected. Sure, you could do this in several more complicated ways but I see nothing wrong in using bit manipulation operators if the context fits as it does in your case. After all these operators are part of the Java core language and are not marked as @deprecated or @evil.

0

精彩评论

暂无评论...
验证码 换一张
取 消