Commit c956e17c authored by Christopher Aue's avatar Christopher Aue

Replaced Array#each with while loop for performance reasons

Example benchmark:
$ time build/bench/bin/mruby -e "Array.new(2_000_000){ |i| i }.index{ |i| i == 1_999_999 }"

Before:
real    0m0.934s
user    0m0.922s
sys     0m0.003s

After:
real    0m0.590s
user    0m0.583s
sys     0m0.007s
parent 6c9013e2
...@@ -101,8 +101,19 @@ class Array ...@@ -101,8 +101,19 @@ class Array
hash = {} hash = {}
array = [] array = []
elem.each { |x| hash[x] = true } idx = 0
self.each { |x| array << x unless hash[x] } len = elem.size
while idx < len
hash[elem[idx]] = true
idx += 1
end
idx = 0
len = size
while idx < len
v = self[idx]
array << v unless hash[v]
idx += 1
end
array array
end end
...@@ -137,12 +148,21 @@ class Array ...@@ -137,12 +148,21 @@ class Array
hash = {} hash = {}
array = [] array = []
elem.each{|v| hash[v] = true } idx = 0
self.each do |v| len = elem.size
while idx < len
hash[elem[idx]] = true
idx += 1
end
idx = 0
len = size
while idx < len
v = self[idx]
if hash[v] if hash[v]
array << v array << v
hash.delete v hash.delete v
end end
idx += 1
end end
array array
end end
...@@ -190,13 +210,17 @@ class Array ...@@ -190,13 +210,17 @@ class Array
def flatten!(depth=nil) def flatten!(depth=nil)
modified = false modified = false
ar = [] ar = []
self.each do |e| idx = 0
len = size
while idx < len
e = self[idx]
if e.is_a?(Array) && (depth.nil? || depth > 0) if e.is_a?(Array) && (depth.nil? || depth > 0)
ar += e.flatten(depth.nil? ? nil : depth - 1) ar += e.flatten(depth.nil? ? nil : depth - 1)
modified = true modified = true
else else
ar << e ar << e
end end
idx += 1
end end
if modified if modified
self.replace(ar) self.replace(ar)
...@@ -718,10 +742,14 @@ class Array ...@@ -718,10 +742,14 @@ class Array
return to_enum :select! unless block return to_enum :select! unless block
result = [] result = []
self.each do |x| idx = 0
result << x if block.call(x) len = size
while idx < len
elem = self[idx]
result << elem if block.call(elem)
idx += 1
end end
return nil if self.size == result.size return nil if len == result.size
self.replace(result) self.replace(result)
end end
...@@ -743,8 +771,9 @@ class Array ...@@ -743,8 +771,9 @@ class Array
if block if block
idx = 0 idx = 0
self.each do |*e| len = size
return idx if block.call(*e) while idx < len
return idx if block.call self[idx]
idx += 1 idx += 1
end end
else else
......
...@@ -46,7 +46,12 @@ class Array ...@@ -46,7 +46,12 @@ class Array
def collect!(&block) def collect!(&block)
return to_enum :collect! unless block return to_enum :collect! unless block
self.each_index { |idx| self[idx] = block.call(self[idx]) } idx = 0
len = size
while idx < len
self[idx] = block.call self[idx]
idx += 1
end
self self
end end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment