上期我们测试了Java和PHP在生成md5密码方面的速度,在相同的机器上,Spring Boot(在OpenJDK 18.9环境下)成绩约为19毫秒,JSP在tomcat(OpenJDK 1.8)环境下,也能够达到13毫秒左右,可以看出,并没有因为JDK升级和编译封装提升太多速度,我们将PHP版本由默认的5.2升级到了8.1以后,PHP可以在8毫秒内完成,比5.2缩短了6毫秒,着实有些意外,PHP在那次测试中完胜Java。
然而,在接下来的对比测试中PHP数组排序,PHP的表现就有些堪忧了。
我们随机生成10000个随机整数,然后再对这些数字排序,最后打印出前面10个和后面10个数字,先上程序:
Java Spring Boot
package com.example.demo;
import java.util.Random;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class mysort {
@RequestMapping("/mysort")
@ResponseBody
public String mysort(Integer gs) {
int csgs=1000;
if(gs!=null)csgs=gs.intValue();
return doSort(csgs);
}
private String doSort(int cs) {
long startTime = System.currentTimeMillis();
StringBuffer otxt=new StringBuffer();
Random random=new Random();
int[] data=new int[cs];
int tmp;
for(int i=0;i=0;i--) {
for(int j=0;j=10 && i");
otxt.append(i);
otxt.append(':');
otxt.append(data[i]);
}
String rtxt=otxt.toString();
long endTime=System.currentTimeMillis();
return "耗时:"+(endTime-startTime)+"毫秒
"+rtxt;
}
}
PHP:
<?php
$t1=microtime(true);
$cs=empty($_GET['gs'])?1000:intval($_GET['gs']);
$data=array();
$tmp=0;
$otxt='';
for($i=0;$i<$cs;$i++)$data[$i]=rand(0,9999);
for($i=$cs-1;$i>=0;$i--){
for($j=0;$j<$i;$j++){
if($data[$j]<$data[$j+1]){
$tmp=$data[$j];
$data[$j]=$data[$j+1];
$data[$j+1]=$tmp;
}
}
}
for($i=0;$i<$cs;$i++){
if($i>=10 && $i<$cs-10)continue;
$otxt=$otxt.' '.$i.':'.$data[$i];
}
$t2=microtime(true);
$t3=intval(($t2-$t1)*1000);
echo '耗时:'.$t3.'毫秒'.$otxt;
?>
经过10次运算,Java平均耗时仅177.8毫秒,而PHP平时耗时达到了恐怖的1975.5毫秒,如果把PHP版本换成5.2版权,这个时间甚至达到6000毫秒以上。

相同的机器,Java比PHP快了10倍以上
Java 用的OpenJDK18.9
PHP用的8.1.1

Java对10000个随机数排序

PHP对10000个随机数排序
PHP是一种弱类型的语言,它对变量类型不敏感,它的每一个变量存储在一个名字zval的结构体里面,数组是一个名为hashTable的结构体,数组元素存储在bucket的结构体中,经过一系统的折腾,不管是对于数组的查询还是修改,效率远低于Java,刚才的程序,即便是跳过排序操作,仅做那个嵌套循环,也需要200多毫秒才能完成。
for($i=0;$i<$cs;$i++)$data[$i]=rand(0,9999);
for($i=$cs-1;$i>=0;$i--){
for($j=0;$j<$i;$j++){
//删除了此处的排序操作
}
}
for($i=0;$i<$cs;$i++){
if($i>=10 && $i<$cs-10)continue;
$otxt=$otxt.' '.$i.':'.$data[$i];
}

仅作嵌套循环,不排序也要花207毫秒
总结:PHP从5.2升级到8.1后,性能提升很明显,但面对复杂的运算,Java的数据组织和运算效率远高于PHP。
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|