内存管理
- 对象复用:避免频繁创建和销毁对象。例如,在循环中创建字符串对象时,可以预先初始化一个字符串变量,然后在每次循环中修改其值,而不是每次都创建新的字符串。
# 不优化的写法
result = []
1000.times do |i|
new_str = "Iteration #{i}"
result << new_str
end
# 优化写法
result = []
str = "Iteration "
1000.times do |i|
str[10..-1] = i.to_s
result << str.dup
end
- 及时释放内存:确保不再使用的对象能及时被垃圾回收。对于大对象,在使用完后将其赋值为
nil
,触发垃圾回收机制。
big_array = Array.new(1000000) { rand(100) }
# 使用 big_array 进行某些操作
big_array = nil
GC.start
- 避免内存泄漏:仔细检查代码中是否存在对象之间的循环引用,这可能导致垃圾回收器无法回收相关对象。例如,确保对象之间的引用关系是合理且可断开的。
算法优化
- 选择合适的数据结构:根据实际需求选择恰当的数据结构。例如,如果需要快速查找元素,使用哈希表(
Hash
)比数组更合适。
# 使用数组查找元素
arr = [1, 2, 3, 4, 5]
if arr.include?(3)
puts "Found"
end
# 使用哈希表查找元素
hash = {1 => true, 2 => true, 3 => true, 4 => true, 5 => true}
if hash[3]
puts "Found"
end
- 优化算法复杂度:尽量使用低复杂度的算法。例如,使用二分查找(
bsearch
)代替线性查找来提高查找效率。
sorted_arr = (1..100).to_a
# 线性查找
arr.index(50)
# 二分查找
sorted_arr.bsearch { |num| num == 50 }
异步处理
- 使用线程或协程:Ruby的
Thread
类可以实现多线程处理,对于一些I/O密集型任务(如文件读取、网络请求),可以将其放到单独的线程中执行,避免阻塞主线程。
require 'thread'
io_thread = Thread.new do
File.read('large_file.txt')
end
# 主线程继续执行其他任务
other_task = "Doing other things"
result = io_thread.join
- 使用事件驱动编程:结合
EventMachine
等库进行事件驱动编程,在处理多个I/O操作时,能够更高效地利用资源。例如,在处理多个网络连接时,事件驱动模型可以在等待一个连接的响应时,继续处理其他连接的事件。
require 'eventmachine'
class EchoServer < EventMachine::Connection
def receive_data(data)
send_data data
end
end
EventMachine.run do
EventMachine.start_server('0.0.0.0', 8080, EchoServer)
end