我想知道你们中是否有人可以帮助我确定为什么我的简单测试应用程序给了我如此不同的结果。我编写了两个测试程序,它们执行一个简单的数据库查询并循环遍历结果。第一个是用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: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版本的实现方式中是不可能的。