skip to Main Content

Context

I am looking at a couple of Java Redis clients like Lettuce and Jedis. I see that both libraries have defined their methods to return boxed primitive types rather than straight primitives.

For example, sadd() returns Long rather than just long.
https://lettuce.io/lettuce-4/release/api/com/lambdaworks/redis/api/sync/RedisSetCommands.html#sadd-K-V…-
and
https://github.com/xetorthio/jedis/blob/d7aba13a8b65e66dedc01c51b73e3794cbe68a62/src/main/java/redis/clients/jedis/commands/BinaryJedisCommands.java#L139

Question

What could be the reason for returning boxed primitives?
From what I understand boxing adds performance overhead.

Would it make sense for my library which uses Redis library, to keep and the return values boxed and propagate it to users of the library?

Edit: None of the methods return null, so encoding special meaning to null does not apply to them.

2

Answers


  1. Boxed primitives can be used in Collections whereas regular primitives can’t (although they can still be added to a Collection of the corresponding boxed type), and also allow you to work with references instead of values, which saves time and space in some circumstances (i.e when the size of the reference is smaller than the size of the data). But as you say, boxed primitives incur the costs of memory and performance overhead.

    Login or Signup to reply.
  2. In my opinion the main reason is to ability to retrieve an Object instead of a primitive type. E.g. it’s possible to retrieve null.

    Numeric wrappers like Integer, Long… are cached values between around -128; +127. All other values will be duplicated in memory. Moreover to store Long it takes over 3 times more space than store long.

    In general case I following following rule.
    If you do not need to return null you should prefer to return a primitive value than numeric wrapper.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search