Why is Python socket is 4.5x slower than Java socket to connect?

  java, performance, python, sockets

I tested Python sockets vs Java sockets and I found out that Python takes 4,5x longer to connect to an server than Java.

Python code:

import socket, time

ip = "74.125.20.147" #ip of www.google.com
port = 80

def main():
  st = time.time()
  for i in range(10000):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))
  ed = time.time()
  print(ed-st)

main()

Java code:

import java.net.*;
import java.io.IOException;
import java.lang.System.*;

class test{
  public static void main(String[] args)throws IOException{
    long st = System.currentTimeMillis();

    for (int i = 0;i<10000;i++){
      Socket s = new Socket();
      s.connect(new InetSocketAddress("74.125.20.147", 80));
    }
    
    long ed = System.currentTimeMillis();

    System.out.print(ed-st);
  }
}

Results:

Python: 27 seconds (27.012101888656616 ms)

Java: 6 seconds (6.569 ms)

I don’t know what is wrong. I ran both on same machine and both are connecting to the same ip.

I searched about python sockets and java sockets, i tryed to change my python code to use classes and tryed to change DNS (even thought i was connecting to an ipv4 not domain) but nothying worked…
I have tried using socket options but they didnt worked aswell

Why does python takes 4,5x longer to connect since both scripts are doing the same work ?

Source: Python Questions

LEAVE A COMMENT