Java is used as a cron script to interact with MySQL and PHP

I currently have some Java programs that use cron to read and update MySQL databases

I'm considering porting the code to PHP Before I did this, I did a simple benchmark to select all rows in a table and store the values in a string

I cycled 10000 times for PHP and Java programs PHP runs it in 5 seconds Java took about a minute

I was surprised by the difference in performance Is that right? Is java really slow? Or did I do something wrong?

I am currently using JDK 6 and PHP cli 5.3 to run cron scripts in CentOS 5.5

This is the code in Java:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Test {
  private Connection connection = null; 
  private Statement statement = null;

  public static void main(String args[]) 
  {
    (new test()).run();
  }

  private void initDB() {
    try {
      String url="jdbc:MysqL://localhost:3306/db";
      Class.forName( "org.gjt.mm.MysqL.Driver" ); 
      connection = DriverManager.getConnection(url,"username","password");
      statement = connection.createStatement();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private String getUserProfiles() 
  {

    String query = "SELECT * FROM UserProfile;";
    String output = "";
    try 
    {
        for(int i = 0; i < 10000; ++i)
        {
            ResultSet rs=statement.executeQuery(query);
            while(rs.next())
                output += rs.getString("name");
        }
    } 
    catch (Exception e) 
    {
      e.printStackTrace();
    }

    return output;
  }

/More code continue/

Then in PHP:

try 
{
    $db = new PDO("MysqL:host=localhost;dbname=db;charset=utf8",'username','password');
    $str = "";
    for($i=0; $i < 10000; ++$i)
    {
        $qry = $db->prepare('SELECT * FROM UserProfile;');

        $qry->execute();
        $result = $qry->fetchAll(PDO::FETCH_OBJ);
        foreach($result as $profile)
        {
            $str .= $profile->name;
        }   
    }
}
catch(PDOException $e)
{
    echo $e->getMessage();
    exit;
}

Solution

In this case, you can use StringBuffer to improve the string performance of Java

private String getUserProfiles() 
{
    String query = "SELECT * FROM UserProfile;";
    StringBuffer output = new StringBuffer();
    try
    {
        for(int i =0; i < 10000; ++i)
        {
            ResultSet rs=statement.executeQuery(query);
            while(rs.next())
                output.append(rs.getString("name"));
        }
    } 
    catch (Exception e) 
    {
      e.printStackTrace();
    }
    return output.toString();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>