3 ms·
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 tha
by cogman10 8mo ago
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.
- Okx 8mo agomaybe 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.
- cogman10 8mo agoFair point, but it is possible this isn't a list but rather some sort of iterable. Those can be boundless. Practically speaking, that would be pretty unusual. I don't think I've ever seen that sort of construct in my day to day coding (which could realistically have more than 1B elements).
- wood_spirit 8mo agoAlso zap the timestamp instant objects if you really need speed; see https://github.com/williame/TimeMillis https://github.com/williame/TimeMillis