我想知道你们中是否有人可以帮助我确定为什么我的简单测试应用程序会给我如此不同的结果。我制作了两个测试程序,它们进行简单的数据库查询并循环遍历结果。第一个是用 PHP 制作的,第二个是用 Java 制作的。
我知道 Java 的性能会更好,但我很难相信 Java 的性能会提高近 20 倍(见下面的结果)。
PHP:
$sql = "select * from message where user_id=20";
$db = get_PDO();
$stm = $db->prepare($sql);
for($i=0;$i<10000;$i++)
{
echo $i."\n";
$res = $stm->execute();
$rows = $stm->fetchAll();
}
echo "done";
get_PDO 只是一个连接到数据库并返回一个pdo 对象的函数。
Java:
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
Statement st= null;
try
{
String userName = ""; // db username
String password = ""; // db password
String url = "jdbc:mysql://localhost/test"; //test = db name
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server: "+e.toString());
}
finally
{
if (conn != null)
{
String query="select * from message where user_id=20";
try{
st = conn.createStatement();
}
catch(Exception e)
{
e.printStackTrace();
try{
conn.close();
}
catch(Exception er) {}
return;
}
for(int i=0;i<10000;i++)
{
System.out.println(i);
try
{
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
结果:
我用时间来衡量性能。 (即时间 php test.php 和时间 java Connect)
PHP:
real 1m34.337s
user 1m32.564s
sys 0m0.716s
Java:
real 0m5.388s
user 0m4.428s
sys 0m0.972s
Java 真的那么快还是我做了什么蠢事? :)
最佳答案
- 根据消息的数量,PHP 可能需要更多的内存,因为完整的结果集在调用
fetchAll()
后保留。 - AFAIK PHP 为结果创建一个关联数组,这也可能很耗时。
- 可能是在 PHP 中,您通过调用
fetchAll()
从数据库中检索所有数据,而在 Java 中,您只需使用rs.next() 遍历结果集
没有实际阅读。根据 JDBC 驱动程序的实现,这可能会提供优化的机会,这在 PHP 版本的实现方式中是不可能的。
关于进行简单的 sql 查询时,Java vs PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771484/