3
2

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.

空の配列への書き込みベンチマーク

Posted at

任意の配列のデータを空の配列に移し替える幾つかのベンチマーク取ってみた

この例だと、配列Wのデータを配列WWに1つずつ逆順に移し替えるもの。
現実的な場面としてはランダムな順番に入れ返るケースを想定してのベンチマーク

case1: 配列Wのデータを末尾から抜いて、空の配列WWの頭からプッシュしていく
case2: 配列WWの長さを配列Wの長さに指定しておいて、配列Wのデータを末尾から抜いて、配列WWの適当な位置に置く
case3: 配列Wのデータを頭から抜いて、空の配列WWの頭に差し込む

結果としては、case2が一番早くて、若干case1が遅くなる。case3はかなり遅い

array_benchmark.js
var Benchmark = require('benchmark')
var words = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'

function not_set_length () {
    var w = words.split(' ')
    var ww = []
    while (w.length) {
        ww.push(w.pop())
    }
    return true
}
function set_length () {
    var w = words.split(' ')
    var ww = []; ww.length = w.length
    var i = 0
    while (w.length) {
        ww[i++] = w.pop()
    }
    return true
}
function maybe_most_slowly () {
    var w = words.split(' ')
    var ww = []
    while (w.length) {
        ww.unshift(w.shift())
    }
    return true
}


(new Benchmark.Suite)
.add('配列の長さを事前に指定する',function () {
    set_length()
})
.add('配列の長さを指定しない', function () {
    not_set_length()
})
.add('配列の長さを指定しない かつ unshift() で足す', function () {
    maybe_most_slowly()
})

.on('cycle', function (ev) {
    console.log(String(ev.target))
})
.on('complete', function () {
    console.log('Fastest is ' + this.filter('fastest').pluck('name'))
})

.run({async: true})
benchmark.txt
配列の長さを事前に指定する x 1,227,097 ops/sec ±1.26% (90 runs sampled)
配列の長さを指定しない x 1,141,372 ops/sec ±0.42% (96 runs sampled)
配列の長さを指定しない かつ unshift() で足す x 227,978 ops/sec ±0.47% (91 runs sampled)
Fastest is 配列の長さを事前に指定する
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?