B4J Question How to logically shift an Int efficiently?

avalle

Active Member
Licensed User
Longtime User
I need to create the equivalent of the >>> Java operator (logical shift) for Int variable (32-bit) with the fastest code as possible in B4J.
The function is extensively used in some crypto related work which would be computed millions of times.

I have created this but I'm not sure if it's the best in terms of performance:
B4X:
Private Sub LogicShift(n As Int, shift As Int) As Int
    For i = 1 To shift
        n = Bit.Or(Bit.UnsignedShiftRight(n, 1), Bit.ShiftLeft(Bit.And(n, 1), 31))
    Next
    Return n
End Sub

Thanks in advance if you have anything better to suggest, also using native Java code eventually.
Andrea
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
One of the changes in B4i v5.00 was to allow methods such as this one to be inlined and be implemented with the shift operator directly. When used properly and in cases where the method is called very very frequently it makes a big difference in iOS.

The reason that the same mechanism is not used in B4A and B4J is that the Java VM is more sophisticated and it does similar optimizations automatically so the performance improvements are not significant (based on my tests).

Make sure to always test performance in release mode.
 
Upvote 0
Top