Is java.util.Scanner that slow?

后端 未结 7 1671
悲&欢浪女
悲&欢浪女 2021-02-07 08:17

In a Android application I want to use Scanner class to read a list of floats from a text file (it\'s a list of vertex coordinates for OpenGL). Exact code is:

Sc         


        
7条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 09:12

    As other posters have stated it's more efficient to include the data in a binary format. However, for a quick fix I've found that replacing:

    scanner.nextFloat();
    

    with

    Float.parseFloat(scanner.next());
    

    is almost 7 times faster.

    The source of the performance issues with nextFloat are that it uses a regular expression to search for the next float, which is unnecessary if you know the structure of the data you're reading beforehand.

    It turns out most (if not all) of the next* use regular expressions for a similar reason, so if you know the structure of your data it's preferable to always use next() and parse the result. I.E. also use Double.parseDouble(scanner.next()) and Integer.parseInt(scanner.next()).

    Relevant source: https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/util/Scanner.java

提交回复
热议问题