単純なテスト アプリケーションでこれほど異なる結果が得られた理由を特定するのを手伝ってくれる人がいるかどうか疑問に思っていました。簡単なデータベース クエリを作成し、結果をループする 2 つのテスト プログラムを作成しました。1 つ目は PHP を使用して作成され、2 つ目は 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 オブジェクトを返す単なる関数です。
ジャワ:
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
ジャワ:
real 0m5.388s
user 0m4.428s
sys 0m0.972s
Javaは本当にそんなに速いのですか、それとも私は何かばかげたことをしましたか? :)