【发布时间】:2013-05-22 05:02:56
【问题描述】:
我想知道是否有人可以帮助我确定为什么我的简单测试应用程序会给出如此不同的结果。我制作了两个测试程序,它们可以进行简单的数据库查询并循环遍历结果。第一个是用 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真的那么快还是我做了一些愚蠢的事情? :)
【问题讨论】:
-
真的没有线索,但也许 java 用“st.executeQuery(query)”做了某种结果缓存?
-
嗯。我在循环内移动了 createStatement() 部分。结果有点变化。现在它使用 java 给出以下结果: real 0m13.731s user 0m44.996s sys 0m3.740s
-
哦,我的错。我没有在该循环内的任何地方添加 st.close() 。之后消耗的时间又回到了真正的 0m6.542s user 0m5.852s sys 0m0.848s
-
在循环内移动 createStatement() 真的没有用。你也不用 PHP 做。
-
我只是想看看语句对象是否缓存了查询。我的理论是,如果我删除并创建新的语句对象,我最终将没有缓存。那会回答我的部分问题:)