簡單比較一下php7和java8的計算和字符串操作性能。
機器:osx 10.10 intel corei5 4GB
php7.php:
- <?php
- $t1 = microtime(true);
- for($i=0; $i<10000000; $i++){
- aaa($i);
- }
- $t2 = microtime(true);
- echo 'php time:' . ($t2 - $t1)*1000 . "ms\n";
- function aaa($i){
- $a = $i + 1;
- $b = 2.3;
- $s = "abcdefkkbghisdfdfdsfds";
- if($a > $b){
- ++$a;
- }else{
- $b = $b + 1;
- }
- if($a == $b){
- $b = $b + 1;
- }
- $c = $a * $b + $a / $b - pow($a, 2);
- $d = substr($s, 0, strpos($s, 'kkb')) . strval($c);
- }
- ?>
java8.java:
- public class Main
- {
- public static void main(String[] args)
- {
- long t1 = System.currentTimeMillis();
- for(int i=0; i<10000000; i++){
- aaa((float)i);
- }
- long t2 = System.currentTimeMillis();
- System.out.println("java time:" + String.valueOf(t2 - t1) + "ms");
- }
- static void aaa(float i){
- float a = i + 1;
- float b = 2.3f;
- String s = "abcdefkkbghisdfdfdsfds";
- if(a > b){
- ++a;
- }else{
- b = b + 1;
- }
- if(a == b){
- b = b + 1;
- }
- float c = (float) (a * b + a / b - Math.pow(a, 2));
- String d = s.substring(0, s.indexOf("kkb")) + String.valueOf(c);
- }
- }
node5.js:
- var t1 = (new Date()).getTime();
- for(var i=0; i<10000000; i++){
- aaa(i);
- }
- var t2 = (new Date()).getTime();
- console.log("nodejs time:" + (t2 - t1) + "ms");
- function aaa(i){
- var a = i + 1;
- var b = 2.3;
- var s = "abcdefkkbghisdfdfdsfds";
- if(a > b){
- ++a;
- }else{
- b = b + 1;
- }
- if(a == b){
- b = b + 1;
- }
- var c = a * b + a / b - Math.pow(a, 2);
- var d = s.substring(0, s.indexOf("kkb")) + c.toString();
- }
lua5.2.lua
- function aaa(i)
- a = i + 1
- b = 2.3
- s = "abcdefkkbghisdfdfdsfds"
- if(a > b) then
- a = a+1
- else
- b = b + 1
- end
- if(a == b) then
- b = b + 1
- end
- c = a * b + a / b - math.pow(a, 2)
- d = string.sub(s, 0, string.find(s, "kkb")) .. tostring(c)
- end
- t1 = os.clock()
- for i=0, 10000000, 1 do
- aaa(i)
- end
- t2 = os.clock()
- print("lua time:" .. (t2 - t1) * 1000 .. "ms")
分別執行1000萬次計算,依次執行以下命令:
java -jar java8jar
node node5.js
php php7.php
luajit lua5.2.lua
lua lua5.2.lua
結果:
結論:由此可見就計算性能來說,java8 > nodejs5 > php7 > luajit > lua
java8是php7的5.2倍,nodejs5是php7的1.8倍,php7和luajit相當。
說lua是最快的腳本,那是往事了。靜態語言的計算性能肯定比動態語言強很多。
對於密集計算,java是最好的選擇;考慮到web的性能的瓶頸往往在數據庫和IO,nodejs和php都是很好的選擇。我個人喜歡php,無論從開發和部署,都比nodejs順心點。
特別注意:如果function aaa(i)中沒有參數i,那麼nodejs是最快的,1000ms就完成了,估計nodejs對相同的執行結果進行了緩存。有好多人都犯了這個錯誤,測試下來就認爲nodejs比java快多了。