Better way to repeatedly use characters from a string in Java

时间:2017-08-30 20:54:14

标签: java string performance

I would like to use characters from a string for many times and wonder if it is better to use string.charAt() everytime I need a character, or save the char array with string.toCharArray() and use index to access character in array. So I wrote a simple benchmark program and I observed a significant performance difference.

this.numRows = 0

and the result is

map

I wonder why charAt() is slower than direct access with array? I checked the implementation of chatAt() and I see no difference with array direct access method.

<div>
        <p>Number of rows = {this.numRows}</p>
        {this.state.members.map((member) => {
          if (member.display) {
            this.numRows++;
            return <p>{ member.name }</p>  
          }
        })}
      </div>

1 个答案:

答案 0 :(得分:2)

使用toCharArray()会带来初始成本,即复制String的内部数组。

从那时起,它就是对数组的简单访问(在返回值时,charAt()中也会发生隐式边界检查)。调用charAt()会带来函数调用和重复边界检查的代价(抛出StringIndexOutOfBoundsException而不是ArrayIndexOutOfBoundsException)。

这种效果是众所周知的,并且已经在Java早期性能书中提到过。

简而言之:如果您只访问String中的单个字符,那么最好使用charAt()。如果您访问更多或所有字符并且字符串可能更长,那么最好使用toCharArray()并改为通过数组。