2

文字列全体の長さが事前にわかっている場合に、複数の短い文字列を連結することにより、長いバイト文字列 (またはバイト配列) を作成する最も効率的な方法を見つけようとしています。私はこのスクリプトを作成し、これらの結果を思いつきました:

import time

MSG = b'test message'
COUNT = 30000

def bytes_list_test():  
    tStart = time.clock()
    l = []
    for i in range(COUNT):
        l.append(MSG)
    bs = b''.join(l)
    print('byte list time:', time.clock() - tStart)

def bytearray_test():
    tStart = time.clock()
    ba = bytearray()
    for i in range(COUNT):
        for c in MSG:
            ba.append(c)
    print('array time:', time.clock() - tStart)

def initialized_bytearray_test():
    tStart = time.clock()
    ba = bytearray([0x00]*len(MSG)*COUNT)
    for i in range(COUNT):
        ba[i*len(MSG):i*len(MSG)+len(MSG)] = MSG
    print('initialized array time:', time.clock() - tStart)

bytes_list_test()
bytearray_test()
initialized_bytearray_test()

結果:

byte list time:         0.0076534920117410365
array time:             0.08107178658246994
initialized array time: 0.08843219671325642

いくつかの質問:

1) バイトのリストを作成し、join() メソッドを使用することは、結果から暗示される方法ですか?

2) バイトのリストを使用する方が、このタイプのために設計されているように見える bytearray を使用するよりもはるかに高速なのはなぜですか?

3) 初期化された配列のサイズを変更する必要がないため、初期化された配列は初期化されていない配列よりも高速であると考えられます (パフォーマンスが向上することもありますが、それほどではなく、一貫性がないことに注意してください)。スライス操作のおかげで速くないですか?

4

1 に答える 1