One line by Java 8 Lambads/Stream APIs


  • 2
    X
    return s.chars().reduce(0, (sum, e) -> sum * 26 + (e - 'A' + 1));
    

  • 0
    N

    It's clean and simple code, but keep in mind that java 8 functional style is 5 times slower than imperative style


  • 0
    X

    It's right. I did some tests before. Lambdas/Stream APIs is about 2 ~ 10 times slower than the imperative style for SIMPLE tasks. But we should not/don't need to worry about it because:

    1. If your program/application is as simple as this question, your application will be fast enough to handle the traffic or meet the requirements in most scenarios.
      2, If your program/application is bit more complicate(e.g. IO/Network/db operation involved). The performance reduced by Lambdas/Stream APIs can be totally ignored.

    My personal opinions, If you want or like Lambdas/Stream APIs, just use it, as long as it can simplify you code and improve the readability.

    Here is the performance test I did for this question:

    final String s = "WVZABDCYXML";
    
    public static int titleToNumber(final String s) {
        int res = 0;
        for (int i = 0, len = s.length(); i < len; i++) {
            char ch = s.charAt(i);
            res = res * 26 + (ch - 'A' + 1);
        }
        return res;
    }
    
    public static int titleToNumber2(final String s) {
        return s.chars().reduce(0, (sum, e) -> sum * 26 + (e - 'A' + 1));
    }
    

    It took about 0.0009 milliseconds for titleToNumber and 0.0011 milliseconds for titleToNumber2. In other words, both methods are able to handle 1 million requests/per second/per thread.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.