From: Massimiliano Mirra Date: 2001-12-26T03:47:41+09:00 Subject: [ruby-talk:29414] Surprise (?) with sockets I took for granted that one socket opening and closing, plus three puts and gets, would be faster than *three* socket opening and closing, plus three puts and gets. Well, it looks like I'm wrong. In fact this is the output of the attached code: Loaded suite Test Started... ...Three puts and gets with one-time connections: 0.036726 secs ....Three puts and gets with a persistent connection: 0.162311 secs . Finished in 0.204511 seconds. 2 runs, 6 assertions, 0 failures, 0 errors Four times as slow?! Someone please tell me that there is some macroscopic mistake in the code below (or that this is a bad dream). require 'Lapidary/TestCase' class OneTimeServer def initialize(host, port) @server = TCPServer.new(host, port) end def listen while (session = @server.accept) session.gets session.puts "received" session.close end end end class PersistentServer def initialize(host, port) @server = TCPServer.new(host, port) end def listen while (session = @server.accept) while (line = session.gets) break if line =~ /quit/ session.puts "received" end session.close end end end def prof(message = nil, &block) start = Time.new block.call time = Time.new - start puts "#{message}: #{time} secs" if message time end require 'socket' class Test < Lapidary::TestCase def initialize(*args) super Thread.new { OneTimeServer.new('localhost', 8888).listen } Thread.new { PersistentServer.new('localhost', 9999).listen } end def testOneTime prof('Three puts and gets with one-time connections') { 3.times { socket = TCPSocket.new('localhost', 8888) socket.puts "something" assert_equal "received\n", socket.gets } } end def testPersistent socket = TCPSocket.new('localhost', 9999) prof('Three puts and gets with a persistent connection') { 3.times { socket.puts "something" assert_equal "received\n", socket.gets } } end end if $0 == __FILE__ require 'Lapidary/UI/Console/TestRunner' Lapidary::UI::Console::TestRunner.run(Test) end