Shouldn't “static” patterns always be static?

前端 未结 5 1508
名媛妹妹
名媛妹妹 2021-01-01 10:42

I just found a bug in some code I didn\'t write and I\'m a bit surprised:

Pattern pattern = Pattern.compile(\"\\\\d{1,2}.\\\\d{1,2}.\\\\d{4}\");
Matcher matc         


        
相关标签:
5条回答
  • 2021-01-01 10:51

    Yes, compiling the Pattern on each use is wasteful, and defining it statically would result in better performance. See this SO thread for a similar discussion.

    0 讨论(0)
  • 2021-01-01 10:57

    Static Patterns would remain in memory as long as the class is loaded.

    If you are worried about memory and want a throw-away Pattern that you use once in a while and that can get garbage collected when you are finished with it, then you can use a non-static Pattern.

    0 讨论(0)
  • 2021-01-01 11:11
    1. Yes, the whole point of pre-compiling a Pattern is to only do it once.
    2. It really depends on how you're going to use it, but in general, pre-compiled patterns stored in static fields should be fine. (Unlike Matchers, which aren't threadsafe and therefore shouldn't really be stored in fields at all, static or not.)

    The only caveat with compiling patterns in static initializers is that if the pattern doesn't compile and the static initializer throws an exception, the source of the error can be quite annoying to track down. It's a minor maintainability problem but it might be worth mentioning.

    0 讨论(0)
  • 2021-01-01 11:11

    first, the bug in pattern is because dot (.) matches everything. If you want to match dot (.) you have to escape it in regex:

    Pattern pattern = Pattern.compile("\\d{1,2}\\.\\d{1,2}\\.\\d{4}");

    Second, Pattern.compile() is a heavy method. It is always recommended to initialize static pattern (I mean patterns that are not being changed or not generated on the fly) only once. One of the popular ways to achieve this is to put the Pattern.compile() into static initializer.

    You can use other approach. For example using singleton pattern or using framework that creates singleton objects (like Spring).

    0 讨论(0)
  • 2021-01-01 11:11

    It is a classical time vs. memory trade-off. If you are compiling a Pattern only once, don't stick it in a static field. If you measured that compiling Patterns is slow, pre-compile it and put it in a static field.

    0 讨论(0)
提交回复
热议问题