logoalt Hacker News

cogman10today at 4:18 PM2 repliesview on HN

Nitpick just because.

Orders by hour could be made faster. The issue with it is it's using a map when an array works both faster and just fine.

On top of that, the map boxes the "hour" which is undesirable.

This is how I'd write it

    long[] ordersByHour = new long[24];
    var deafultTimezone = ZoneId.systemDefault();
    for (Order order : orders) {
        int hour = order.timestamp().atZone(deafultTimezone).getHour();
        ordersByHour[hour]++;
    }
If you know the bound of an array, it's not large, and you are directly indexing in it, you really can't do any better performance wise.

It's also not less readable, just less familiar as Java devs don't tend to use arrays that much.


Replies

wood_spirittoday at 4:45 PM

Also zap the timestamp instant objects if you really need speed; see https://github.com/williame/TimeMillis

Okxtoday at 4:32 PM

maybe it would be a little better to use ints rather than longs, as Java lists can't be bigger than the int max value anyways. Saves you a cache line or two.

show 1 reply