LoginSignup
7
7

More than 5 years have passed since last update.

Integer#valueOfとparseIntのパフォーマンス測定

Posted at

動機

自分が今見ているシステムでFindBugsを2.0.2から3.0.1に上げたらDM_BOXED_PRIMITIVE_FOR_PARSINGという重要度Highの警告が大量に発生してしまった。
内容的にはNumber#valueOfでボクシングされた値をプリミティブな変数に代入しているのでパフォーマンス的にアレですよ、Number#parseXXXを使いましょうねって感じ(だと認識しています)

String num = "1";
// ダメ
int hoge = Integer.valueOf(num);
// こっちの方が良い
int hoge = Integer.parseInt(num);

測定

以下のコードを使って測定しました。
測定環境は

  • MBP(2GH, 16GB, MacOS10.9.5)
  • jdk1.8.0_25
import java.util.function.Consumer;
import java.util.stream.IntStream;
import java.util.stream.Stream;


public class ConvertIntTest {
    public static void main(String[] args) {
        final int count = Integer.parseInt(args[0]);
        Stream<String> values = IntStream.range(0, count).parallel().boxed().map(String::valueOf);

        if(args[1].equals("valueOf")) {
            test(values, Integer::valueOf);
        } else {
            test(values, Integer::parseInt);
        }
    }

    public static void test(Stream<String> values, Consumer<String> method) {
        long start = System.currentTimeMillis();
        values.forEach(method);
        System.out.println("time: " + (System.currentTimeMillis() - start));
    }
}

結果

確かにparseIntの方が早いけど、valueOfでも1億件でも4秒弱くらいなので、そこまで気にするレベルでもない気もします…w

count valueOf parseInt
100万 約130ms 約110ms
1000万 約500ms 約350ms
1億 約3500ms 約2000ms
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7