0

If I have a Long (not the primitive) whats the best way to convert it to a string. By best, I mean fastest.

Currently, I'm doing this.

Long testLong = 123456L;
return new StringBuilder()
               .append(PREFIX)
               .append("_")
               .append(testLong)
               .toString();

is String.valueOf(testLong) or testLong.toString() better?

  • 1
    Have you tried running any benchmarks to see which fits your need the best? – Dan W Dec 08 '20 at 17:26
  • Don't they both use `static String Long.toString(long)`? – terrorrussia-keeps-killing Dec 08 '20 at 17:27
  • 1
    `String.valueOf(long l)` and the non-static `toString()` method of `Long` both just call the static `Long.toString(long l)` method. So it should be literally no difference at all. – OH GOD SPIDERS Dec 08 '20 at 17:28
  • 1
    What's up with the `PREFIX` and underscore in your stringbuilder? Are you asking how to append a long to a string or how to convert a long (only) to a string? – knittl Dec 08 '20 at 17:29
  • 1
    What you're already doing is best. You will not notice any performance difference between `append(testLong)`, `append(String.valueOf(testLong))`, and `append(testLong.toString())`, so you should write the code that's most **logical**, which is `append(testLong)`. The actual performance difference between those 3 calls is minuscule compared to the actual conversion of a `long` to a `String`. Don't micro-optimize your code like this, write code that makes sense. – Andreas Dec 08 '20 at 17:29

1 Answers1

1

.append(testLong) calls .append(String.valueOf(testLong)).

.append(String.valueOf(testLong)) calls .append((testLong == null) ? "null" : testLong.toString())

.append(testLong.toString()) calls .append(Long.toString(testLong.value)) (where value is the boxed long), which creates a new String

.append(testLong.longValue()) does not create a new String, instead, it writes directly to the StringBuilder byte array.

Therefore the latter is the fastest, if you know that the Long will never be null:

Long testLong = 123456L;
return new StringBuilder()
               .append(PREFIX)
               .append("_")
               .append(testLong.longValue())
               .toString();
spongebob
  • 8,370
  • 15
  • 50
  • 83