Quiz: Which Is Faster?

Which is faster

  • LengthOfLong1

    Votes: 4 25.0%
  • LengthOfLong2

    Votes: 7 43.8%
  • LengthOfLong3

    Votes: 5 31.3%

  • Total voters
    16

wonder

Expert
Licensed User
Longtime User
How about this one?
B4X:
Sub NumberOfDigits(n As Long) As Short
    Dim i = 1 As Short, p = 10 As Long
    Do Until n Mod p = n : p = p * 10 : i = i + 1 : Loop
    Return i
End Sub

Without hacking the generated Java code at compile time (yes, it is possible), this is the cleanest I can get:
B4X:
public static short  _numberofdigits(long _n) throws Exception {
    short _i = (short)0;
    long _p = 0L;
    _i = (short) (1);
    _p = (long) (10);
    while (!(_n%_p==_n)) {
        _p = (long) (_p*10);
        _i = (short) (_i+1);
    }
    ;
    if (true) return _i;
    return (short)0;
}

You could write a clean Java function and call it from a library:
B4X:
public static short  numberofdigits(long n) {
    short i = 1;
    long  p = 10L;
    while (n % p != n) {
        p *= 10;
        ++i;
    }
    return i; 
}
 

keirS

Well-Known Member
Licensed User
Longtime User
I ran the same test code as for the rest. A long is up to 9223372036854775807 in value so a While loop will require up to 19 iterations for the biggest numbers. My test only uses Int so would need up to 9 iterations. Your test is really only going up to a maximum of 5 iterations. As only 1 of the numbers would return 6.
 

keirS

Well-Known Member
Licensed User
Longtime User
How about this one?
B4X:
Sub NumberOfDigits(n As Long) As Short
    Dim i = 1 As Short, p = 10 As Long
    Do Until n Mod p = n : p = p * 10 : i = i + 1 : Loop
    Return i
End Sub

I get 161ms. Anything which uses iteration will not be as fast as using divide and conquer in a simple case like this.
 
Top