Why does String.indexOf() not use KMP?

前端 未结 2 678
一整个雨季
一整个雨季 2020-12-24 14:30

I read the source code of java.lang.String and I was surprised to find that String.indexof() does not use the Knuth–Morris–Pratt algorithm? As we

2条回答
  •  长情又很酷
    2020-12-24 15:05

    KMP has better worst-case performance, but actually requires a little bit of up-front computation (to generate the table of offsets). It also requires an initial memory allocation, which could also impact performance.

    For (presumably) common use-cases of searching in relatively short strings, this might actually end up slower than the primitive implementation.

    This, bundled with the fact that for really huge data sets you will probably be using more specialized data structures than a simple String means that the increased implementation (and possibly runtime) cost is not worth investing.

    Note that this might change in future Java versions, as the actual algorithm is not specified.

提交回复
热议问题