5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LocalDateクラスで月末を取得する方法の速さ比較

Last updated at Posted at 2016-07-27

LocalDateクラスを使って月末を取得する方法について速さを比較してみました。

実行環境は以下の通りです。

  • DELL VOSTRO 1540
  • Windows 10 Pro 32bit
  • Intel Celelron 2.00 GHZ
  • メモリ 2.0GB
  • HDは約300GB

月末を取得するは以下です。

  • rangeメソッドを使用して、月の日について最大を求める。
  • 翌日初日-1を設定して月の日を求める。
  • LocalDate#lengthOfMonthを使う。(@rinp さんにコメントをいただきましたので追加。)

ソースと実行結果

上記をそれぞれ30000回実行して時間を比較しました。以下、ソースと結果です。

ソース
package test;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoField;
import java.util.function.LongSupplier;

public class Test {

    // --計測用--
    private void printProcessingTime(LongSupplier f) {
        int count = 30000;
        long start, end;
        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            f.getAsLong();
        }
        end = System.currentTimeMillis();
        System.out.printf("出力確認:%s, 計測 %3d: ", f.getAsLong(), end - start);
        System.out.println();
    }

    // --計測--
    public static void main(String[] args) {
        new Test().test();
    }

    private void test() {
        System.out.println("rangeメソッドを使用して、月の日について最大を求める。");
        printProcessingTime(() -> {
            return LocalDate.of(2016, Month.FEBRUARY.getValue(), 1).range(ChronoField.DAY_OF_MONTH).getMaximum();
        });

        System.out.println("翌日初日-1を設定して月の日を求める。");
        printProcessingTime(() -> {
            return LocalDate.of(2016, Month.MARCH.getValue(), 1).minusDays(1L).getDayOfMonth();
        });
        System.out.println("LocalDate#lengthOfMonthを使う。");
        printProcessingTime(() -> {
            return LocalDate.of(2016, Month.FEBRUARY.getValue(), 1).lengthOfMonth();
        });
    }
}

以下、実行結果です。

結果
rangeメソッドを使用して、月の日について最大を求める。
出力確認:29, 計測  86: 
翌日初日-1を設定して月の日を求める。
出力確認:29, 計測  26: 
LocalDate#lengthOfMonthを使う。
出力確認:29, 計測   2: 

LocalDate#lengthOfMonthが一番速いです。

修正履歴

20161009

  • 文言修正。
  • 月末取得方法に@rinp さんに教えていただいた方法を追加。
  • ソースを修正し、java.util.functionを使用。
  • 出力結果も再実施。
5
5
8

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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?