Skip to content

Commit 265f33b

Browse files
committed
to_s's inject was AMAZINGLY slow, and added int-boundary test.
1 parent 456625b commit 265f33b

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

lib/bitarray.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def each(&block)
3131

3232
# Returns the field as a string like "0101010100111100," etc.
3333
def to_s
34-
inject("") { |a, b| a + b.to_s }
34+
@field.collect{|ea| ("%032b" % ea).reverse}.join[0..@size-1]
3535
end
3636

3737
# Returns the total number of bits that are set

test/test_bitarray.rb

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,17 @@ def test_random_setting_and_unsetting
3030
end
3131

3232
def test_random_side_effects
33-
ba2 = BitArray.new(1000, 1)
33+
ba2 = BitArray.new(@public_ba.size, 1)
3434

35-
on = 300.times.collect do
36-
index = rand(1000)
35+
on = (@public_ba.size / 2).times.collect do
36+
index = rand(@public_ba.size)
3737
@public_ba[index] = 1
3838
ba2[index] = 0
3939
index
4040
end
41-
1000.times do |i|
41+
assert_equal(@public_ba.to_s, @public_ba.to_s_fast)
42+
43+
@public_ba.size.times do |i|
4244
assert_equal(@public_ba[i], on.include?(i) ? 1 : 0)
4345
assert_equal(ba2[i], on.include?(i) ? 0 : 1)
4446
end
@@ -63,10 +65,9 @@ def test_size
6365
end
6466

6567
def test_to_s
66-
ba = BitArray.new(10)
67-
ba[1] = 1
68-
ba[5] = 1
69-
assert_equal "0100010000", ba.to_s
68+
ba = BitArray.new(35)
69+
[1, 5, 6, 7, 10, 16, 33].each{|i|ba[i] = 1}
70+
assert_equal "01000111001000001000000000000000010", ba.to_s
7071
end
7172

7273
def test_total_set

0 commit comments

Comments
 (0)