Java 作为 cron 脚本与 MySQL 交互 vs 使用 PHP

发布于 2024-10-28 20:45:21 字数 1983 浏览 3 评论 0原文

我目前有一些使用 Cron 读取和更新 MySQL 数据库的 Java 程序。

我正在考虑将代码移植到 PHP。在执行此操作之前,我做了一个简单的基准测试:SELECT特定表中的所有行,然后将值存储在字符串中。

我对 PHP 和 Java 程序都循环了 10,000 次。 PHP 在 5 秒内运行完毕。 Java 大约花了 1 分钟。

我对性能上的差异感到惊讶。这大约是对的吗? Java真的这么慢吗?或者我做错了什么?

我目前正在 CentOS 5.5 中使用 JDK 6 和 PHP CLI 5.3 运行 cron 脚本。

下面是 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;
  }

/更多代码继续/

然后是 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;
}

I currently have a few Java programs that read and update the MySQL database using Cron.

I am considering porting the code to PHP. Before I do this, I did a simple benchmark test of SELECTing all rows in a certain table and then storing the values inside a string.

I loop this 10,000 times for both the PHP and Java programs. PHP ran it in under 5 seconds. Java took around 1 minute.

I was astonished by the difference in performance. Is this about right? Is Java really this slow? Or am I doing something wrong?

I'm currently running the cron scripts in CentOS 5.5 with JDK 6 and PHP CLI 5.3.

Here 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 continues/

And 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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鸠魁 2024-11-04 20:45:21

在这种情况下,您可以通过使用 StringBuffer 来提高 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();
}

you can improve java's string performance in this case by using StringBuffer

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();
}
悲凉≈ 2024-11-04 20:45:21

我确信这在很大程度上取决于您为每种语言编写的代码(与 PHP 相比,Java 代码是什么样的?)。如此大的差异暗示着有些事情是不同的。也许您建立或维护数据库连接的方式?

I'm sure it's going to depend largely on the code you wrote for each language (what does the Java code look like compared to PHP?). Such a large discrepancy hints that something is different. Perhaps the way you're establishing or maintaining database connections?

墨离汐 2024-11-04 20:45:21

差异可能在于您处理结果的方式。在Java版本中,您使用String,这意味着您每次循环都会创建一个新副本。尝试使用 StringBuffer 并追加结果,仅在完成后将其转换为 String。

看看 http://www.velocityreviews.com/forums /t146183-why-string-is-immutable.html 讨论为什么 String 会有这样的行为。

The difference is likely in how you handle the results. In the Java version, you use String, which means you will make a new copy each time in the loop. Try to use StringBuffer and append the result instead, only converting it to String when done.

Have a look at http://www.velocityreviews.com/forums/t146183-why-string-is-immutable.html for a discussion on why String behaves like that.

黑寡妇 2024-11-04 20:45:21

看起来您真正要比较的是一种通过连接来编译非常大的字符串的方法;这不是真正的数据库应用程序可能会做的事情,而且您没有以 Java 中最有效的方式执行此操作(您在 Java 中以糟糕的方式执行此操作)。

我确信您不应该根据这个人为且实施不当的基准来选择语言。

考虑哪种语言的代码更适合您。我建议你用PHP编写,因为从代码来看,你对Java的掌握明显较弱。

It looks like what you're really comparing is a method of compiling very large strings by concatenation; this is not something that a real database application is likely to do, plus you're not doing it in the most efficient way in Java (you are doing it in a terrible way in Java).

I feel sure that you should not base your choice of language on this artificial and badly implemented benchmark.

Consider which language has the easier code for you. I'd suggest you write it in PHP, as from the code, your grasp of Java is clearly weaker.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文