guava
guava copied to clipboard
Refactor use System.arraycopy() to copy array.
I have a question about why should we use System.arraycopy() in this code snippet, for most small arrays, e.g. length less than 50, for-loop is generally faster than system array copy according to benchmark test.
That's unlikely; got a citation for that benchmark?
Not sure the change was a bad idea. (Not sure it's worth changing either, but...)
For case 1:
'x' -> "length less than 50".toCharArray(), the for-loop is better.
For case 2:
'y' -> "length is too long, .................................................".toCharArray(), the System#arrayCopy is better.
Such as.
CharEscaper charEscaper =
createSimpleCharEscaper(
ImmutableMap.<Character, char[]>builder()
.put('x', "length less than 50".toCharArray())
.put('y', "length is too long, .................................................".toCharArray())
.put('z', "<lo>".toCharArray())
.buildOrThrow());
UnicodeEscaper unicodeEscaper = Escapers.asUnicodeEscaper(charEscaper);
unicodeEscaper.escape("xxxxxxx")
Usually, the case 1 is better way, do you think the case 2 is necessary?
It's a little pity that I didn't preserve the benchmark test process and result, but when I continue to run it much more times I start to find that the result is not always like what I am thinking, it looks like unstable, sometimes the system.arraycopy() is faster, but occasionally slower.
I'm having some doubts, maybe my personal computer or environment has impact on the test result, or my test cases are not completely exact, not sure about that.
But anyway, at least I think system.arraycopy() is more brief, although this sounds like not very persuasive. :)
System.arraycopy() should be faster as it's a native call.
I dug up some links for fun:
- https://bugs.openjdk.org/browse/JDK-6912521
- https://bugs.openjdk.org/browse/JDK-8149758
- https://bugs.openjdk.org/browse/JDK-8150730
- https://stackoverflow.com/q/32834869/28465 (from probably before the improvement landed)
[edit: And note that the performance tradeoffs could easily vary based on whether the array is an object array or a primitive array.]
It looks like this code is rarely used (if ever) inside Google, so much so that it doesn't even appear in our global profiling data. I'm also not sure that it's actually even reachable in the open-source release, so maybe I should just remove it....