沒有通用的最佳性能方式。
charAt
進行邊界檢查(但是可以進行優化),而
toCharArray
則使用了臨時空間。
當VM無法消除邊界時,使用
toCharArray
可能會更快。
有關更多資訊,請參見這裡PPT 的
74-78
頁。
在上面的文檔中給出了測試和解釋。
Q: Should I copy out the char[] array or not? 我是否應該複制char[]數組?
A: If you don’t need performance, both approaches are the question of style. 如果你不關心性能,兩種方法隻是風格問題。
Q: I care about performance, should I copy out the char[] array? 我關心性能,是否應該複制char[]數組?
A: You should, in non-trivial case. 是,在特殊情況下
Q: What is considered non-trivial case? 什麼情況?
A: Non-local control flow, volatile reads, etc. that break commonning. 非本地控制流、易失性讀取等會破壞通用性。
Q: This sucks. There is no universal best-performance way? 真糟糕,沒有通用的最佳方法?
A: (silence was the answer, and Engineer left enligthened) (沒有回複,并且離開 ) == 滾
關于JVM消除邊界優化參考:JVM編譯優化技術:數組邊界檢查消除。