My friend and I decided to write similar programs in Java and C# using threads to post data to a website. His Java application runs in about 6 seconds while mine written in C# takes 23 seconds. Looking at my C# code, is there a reason why it is running slow. Are my threads causing false sharing, or is the C# VM slower than Java's?
We are comparing our codes using 4 threads. Also, we are running this on a local server so server response time is not an issue.
C# Code:
MAIN
Thread[] childThread = new Thread[4];
int i, j = 0, skip = 125;
for (i = 0; i < 500; i+=skip, j++) {
threader threader = new threader(tokens.GetRange(i, skip));
List<String> test = tokens.GetRange (i, skip);
int size = test.Count;
childref = new ThreadStart(() => threader.CallToChildThread());
childThread[j] = new Thread(childref);
childThread[j].Start();
}
THREADER
public class threader {
public List<String> tokens;
public threader(List<String> tokens) {
this.tokens = tokens;
}
public void CallToChildThread() {
var watch = System.Diagnostics.Stopwatch.StartNew();
foreach (String item in tokens) {
using (var client = new WebClient()) {
var values = new NameValueCollection();
values["username"] = "blah";
values["password"] = item;
DateTime time = DateTime.Now;
var response = client.UploadValues("http://example.com", values);
if (!isFound) {
var responseString = Encoding.Default.GetString(response);
Console.WriteLine(item + " is a " + responseString);
if (responseString.Equals("valid")) {
isFound = true;
Console.WriteLine('\n');
Console.WriteLine(item + " is a " + responseString);
Console.WriteLine("===================");
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine(elapsedMs / 1000 + " Seconds");
return;
}
} else {
return;
}
}
}
}
}
My friends Java code that runs in 6 seconds is:
THREADER
public class Threader extends Thread{
public List<String> list;
public Threader(List<String> list){
this.list = new ArrayList<String>(list);
}
@Override
public void run() {
try {
for (String item : list) {
String url = "http://example.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
String urlParameters = "username=blah&password="+ item;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
if (!response.toString().equals("invalid")) {
System.out.println("Found it!");
System.exit(0);
}
System.out.println(response.toString() + " for " + item);
}
} catch (Exception e){e.printStackTrace();}
}
}