5
3

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.

vectorにおける[]演算子とat()の速度を比較してみようメモ

Last updated at Posted at 2016-10-31

個人的メモです

  • 検証方法はガバガバかもしれない。

vectorの要素にアクセスするには、[]演算子とat()の2通りがある。

  • []演算子
  • at()

一般的には[]演算子の方を使う。

なぜなら、at()はvectorの中のindexを全て見た上で、要素にアクセスするから。
[]は直接その要素にアクセスするので、パフォーマンスこちらの方が良い。
at()はその性質上デバッグする際に便利なので、開発時に使うものとい割り切った方がいいかもしれない。

速度比較したら、3倍くらい違った。

[]演算子とat()の速度比較を以下の方法で検証。

検証手順

  1. valという100000個のfloat型を用意し、その全てに0を格納。
  2. その状態から、100000回0番目の要素にアクセス
vector<float> vals;
vals.assign(100000, 0.0);

float start = ofGetElapsedTimef();
    cout << "start:" << start << endl;
    
    for(int i = 0; i < vals.size(); i++)
    {
        vals[0]; //or vals.at(0)
    }
    
    float end = ofGetElapsedTimef();
    cout << "end:" << end << endl;
    span = end - start;
    
    cout << "実行時間:" << span << endl;

6回実施した平均の実行速度は以下。

[]演算子 atメソッド
0.044165(ms) 0.111919(ms)
5
3
1

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?