Sobes.tech
Middle

What is faster: a block, a process, or a lambda?

sobes.tech AI

Answer from AI

Lambda and block execute faster than a process.

  • Block ({}) and Lambda (->): These are anonymous functions that execute in the context of the parent process. Creating and executing a block or lambda requires minimal overhead related to context switching, memory allocation for the new process, and inter-process communication.
  • Process (Process.fork or system): Creating a new process involves significant overhead. The operating system must allocate resources for the new process (memory, file descriptors, etc.), copy (or use copy-on-write) the current process's address space, and schedule the new process for execution. Context switching between processes also takes more time than calling a function within a single process.

From a performance perspective:

  1. Block/Lambda: The fastest.
  2. Process: The slowest.

The differences between a block and a lambda in terms of speed are minimal and usually insignificant compared to the differences between them and a process. The key differences between a block and a lambda lie in argument handling and return behavior.

# Example of a block
def call_block
  yield "hello"
  puts "After yield"
end

call_block { |message| puts message } # Outputs "hello", then "After yield"

# Example of a lambda
lambda_proc = ->(message) { puts message }

def call_lambda(lambda_proc)
  lambda_proc.call "world"
  puts "After call"
end

call_lambda(lambda_proc) # Outputs "world", then "After call"

# Example of a process (slower)
# new_process = Process.fork do
#   puts "In new process"
# end
# Process.wait(new_process)
# puts "After process"