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)
Java: 6 seconds (6.569)
I don't know what is wrong. I ran both on same machine and both are connecting to the same IP.
I tried to change my python code to use classes and tried to change DNS (even thought I was connecting to an ipv4 not domain) but nothing worked. I have tried using socket options but they didn't worked either.
Why does python takes 4.5x longer to connect since both scripts are doing the same work?