programming \ java \ programming \ php

java vs php

小编最近经心情不大好,写一篇博文解解闷

在搞清楚java vs php前,我们需要熟悉一些基本概念才能很好的理解下面的对比,否则看了都感觉不知道什么意思

基本概念

1,并发 vs 并行

并发和并行进行区分还是挺简单的,用erlang之父Joe Armstrong画的一张图说明一下:

parallel_vs_concurency

并发是两个队列交替使用一台咖啡机,并行是两个队列同时使用两台咖啡机,如果串行,一个队列使用一台咖啡机,如果前面那个人接好咖啡一直不离开,会导致后面的人都没有咖啡喝.就像程序中一个独享资源被占用,其他线程就处于等待中一样,但是并发通过某种机制,比如时间分片等,规定每个人只能使用咖啡机30秒钟,那么1分钟当中,并发就可以做到2次,所以并发的大小和占用资源的时间是负相关的,资源占用时间短才能够做到高并发

2.吞吐率(Requests per second)

这个比较好理解,每秒能够处理的请求数,越大越好,说白了这个跟发动机功率一样,越大代表性能越强
计算公式:
Request per second = Complete requests / Time taken for tests

3,用户平均请求等待时间Time per request

计算公式:
处理完成所有请求数所花费的时间/ (总请求数 / 并发用户数)
Time per request = Time taken for tests /( Complete requests / Concurrency Level)

4,服务器平均请求等待时间(Time per request: across all concurrent requests)

计算公式:
处理完成所有请求数所花费的时间 / 总请求数
Time taken for / testsComplete requests

php vs java

了解完了上面的这些基本概念,下面我们把PHP和java进行比较,本次实验条件说明(都在小编的电脑上,MacBook Pro Intel Core i7 2.2 GHz memory 16 GB,java和php都没有进行优化,php采用lnmp架构,java采用spring内嵌服务器,都输出一个相同json字符串接口)

对比一
ab -n 100 -c 10 http://192.168.200.299:8080/greeting?name=desheng

item java php
Concurrency Level 10 10
Time taken for tests 0.068 seconds 0.108 seconds
Complete requests 100 100
Failed requests 10 91
Total transferred 15604 bytes 19292 bytes
HTML transferred 3704 bytes 3592 bytes
Requests per second 1477.76 [#/sec] (mean) 922.77 [#/sec] (mean)
Time per request(user) 6.767 [ms] (mean) 10.837 [ms] (mean)
Time per request(server) 0.677 [ms] (mean, across all concurrent requests) 1.084 [ms] (mean, across all concurrent requests)
Transfer rate 225.19 [Kbytes/sec] received 173.85 [Kbytes/sec] received

总结:

  • 从发现Time per request(server)这个指标中,我们可以看出java处理效率比php高,脚本语言不敌伪编译,可以预想的到,如果改成c/c++可能效率提升更加的大
  • 从Requests per second指标中可以看出,java采用的是多线程,php采用的是多进程,java线程可以轻轻松松上千,php只能望洋兴叹了

对比二

ab -n 100 -c 100 http://www.yunying.com/?name=desheng

item java php
Concurrency Level 100 100
Time taken for tests 0.043 seconds 0.130 seconds
Complete requests 100 100
Failed requests 0 90
Total transferred 15700 bytes 19288 bytes
HTML transferred 3800 bytes 3588 bytes
Requests per second 2346.70 [#/sec] (mean) 768.95 [#/sec] (mean)
Time per request(user) 42.613 [ms] (mean) 130.047 [ms] (mean)
Time per request(server) 0.426 [ms] (mean, across all concurrent requests) 1.300 [ms] (mean, across all concurrent requests)
Transfer rate 359.80 [Kbytes/sec] received 144.84 [Kbytes/sec] received

总结:

  • 对比一 vs 对比二中的Time per request(server),java居然越跑越快,php只会越跑越慢,这是因为java开启了JIT,对执行代码进行了优化,但是php没有开启opcahe,所以越来越慢了.
  • 对比Requests per second数据,发现php死活超不了一千的槛,

对比三

ab -n 1000000 -c 1000 http://192.168.200.229:8080/greeting?name=desheng

item java php
Concurrency Level 1000
Time taken for tests 302.511 seconds
Complete requests 1000000
Failed requests 991501
Total transferred 159894503 bytes
HTML transferred 40894503 bytes
Requests per second 3305.66 [#/sec] (mean)
Time per request(user) 30.251 [ms] (mean)
Time per request(server) 0.303 [ms] (mean, across all concurrent requests)
Transfer rate 516.17 [Kbytes/sec] received

总结:

  • java还能跑,但是php已经被压挂了(pr_socket_recv: Connection reset by peer (104)),已经连接不上了

终结:

虽然我很喜欢php简单明了的设计理念,快速并且灵活开发应用,实现功能可以依托大神开发的扩展,但是如果对性能有要求的领域,php就不那么合适了.PHP官网是这么说PHP的:

“PHP is a popular general-purpose scripting language that is especially suited to web development.Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.”

从上面这句话中我们就能感觉到php并没有提到高性能,由此我们彻底的明白了,php面对巨大的编程市场,没有和java一样选择大而全的布局,而是希望有那么一群人,他们希望web编程的成本足够的低,开发的周期足够的短,但是完全能满足日常普通用户的访问需求.就像polo,普通版高尔夫,飞度等车型一样,他只能满足你日常代步的需求,但是你想让他上赛道比赛,输的命运很难改写.所以在创办企业选择编程语言的时候,先看看自己的预算,再看看自己的目标,差不多答案就有了.顺便回答一下facebook为什么用PHP,那是因为facebook刚开始没钱,而且没想到自己有这么火.今天就说到这里吧.时间不早了,洗洗睡吧

文档信息

版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)

本文出自 “richardtumas”的博客,请务必保留此

发表日期: 2017年8月11日

邮件: joy@richardtumas.com

programming \ php

realpath()

mkdir mian
cd main
touch main.php

add below code to main.php

<!--?php include("./sub/sub.php");//whether or not require or include a file change can't change execute path echo "\n" echo realpath("./"); ?-->
mkdir sub;
touch sub.php

add below code to sub.php

<!--?php //chdir("/usr/local/bin");//chdir can change execute path echo realpath("./"); ?-->


conclusion :
execute path can’t changed whether or not is executed in require and include or main php file

programming \ java \ programming

java中的import和package

由于java这门语言没有走正常的路,其他语言采用namespace这个关键字,但是java另辟蹊径,采用package 机制,一个jar包,就是一个相关功能模块的大类,命名方式就是模仿因特网的域名机制,每一个类在本域名下是独一无二的。如果要使用某一个类的就要使用import+域名+类名+方法名,这种语法,支持通配符*。未完待补充

package demo.first;

/**
 * Created by joy on 4/10/2017.
 */
public class Test2 {

    public static void main(String[] args){
        System.out.print("helloworld");
    }

}

 

programming \ php

Some important options maybe useful when compile php from source code

As we know install php 7 in ubuntu can’t use apt-get install php directly,Because official source haven’t updated until now(2016/8/21),but we can compile it from source code ,here I provide some useful options that maybe helpful for your to use php 7,

./configure  '--prefix=/usr/' '--with-config-file-path=/etc/php' '--enable-fpm' '--with-fpm-user=joy' '--with-fpm-group=joy' '--enable-mysqlnd' '--with-mysqli' '--with-pdo-mysql' '--with-iconv-dir' '--with-freetype-dir' '--with-jpeg-dir' '--with-png-dir' '--with-zlib' '--with-libxml-dir' '--enable-xml' '--disable-rpath' '--enable-bcmath' '--enable-shmop' '--enable-sysvsem' '--enable-inline-optimization' '--with-curl' '--enable-mbregex' '--enable-mbstring' '--enable-intl' '--with-mcrypt' '--enable-ftp' '--with-gd' '--enable-gd-native-ttf' '--with-openssl' '--with-mhash' '--enable-pcntl' '--enable-sockets' '--with-xmlrpc' '--enable-zip' '--enable-soap' '--with-gettext' '--disable-fileinfo' '--enable-opcache' '--with-xsl'

Please remember instead DIR with the directory where software are install ed ,If you don’t know where is the path that software installed.you can use which command,Just like below

joy@ubuntu:~/php-7.0.4$ which mysql
/usr/bin/mysql
joy@ubuntu:~/php-7.0.4$ which curl
/usr/bin/curl
joy@ubuntu:~/php-7.0.4$ which openssl
/usr/bin/openssl

If you still can’t compile php 7 because specified error path for configure.then you can leave DIR alone,Just like this

./configure  --with-openssl --with-curl --with-pdo-mysql --with-mysqli= --enable-mbstring

./configure will find default path for you

good luck to you!

 

 

programming \ php

try catch php Exception

Today i met a interesting thing that parent exception can catch sub exception,for example

<?php

class testException extends Exception{
}
class myException extends testException{
}
try{
  try{ 
      try{
         throw new myException();
      }catch(myException $e){
           echo "hello world";
           throw $e;
      }
    }catch(testException $e){
        echo "hello world";
        throw $e;
    }
 }catch(Exception $e){
     echo "hello world";
}
?>

//final result “hello worldhello worldhello world”

you can see subclass exception will be catched by parent class,but subclass exception do not catch parent class exception,blow is example

<?php
class testException extends Exception{

}
class myException extends testException{
 
}
try{
    try{
       throw new Exception();
    }catch(myException $e){
        echo "hello world";
        throw $e;
     }
}catch(testException $e){
    echo "hello world";
}

?>

//result “PHP Fatal error:  Uncaught Exception”

I hope this  may helpful to you.

programming

ASCII Table

ASCII Table and Description

ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as ‘a’ or ‘@’ or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose. Below is the ASCII character table and this includes descriptions of the first 32 non-printing characters. ASCII was actually designed for use with teletypes and so the descriptions are somewhat obscure. If someone says they want your CV however in ASCII format, all this means is they want ‘plain’ text with no formatting such as tabs, bold or underscoring – the raw format that any computer can understand. This is usually so they can easily import the file into their own applications without issues. Notepad.exe creates ASCII text, or in MS Word you can save a file as ‘text only’

 

Ascii Table

 

Extended ASCII Codes

EBCDIC and IBM Scan Codes

programming \ trick

how to mount your file to virtual-machine

  Sometimes I need write code in working computer which is window 10 operate system,but run Php scripts in Linux environment.I don’t ensure every code that wrote by me is completely correct.So I want to test in Linux environment.Maybe you can upload codes to your server,but I don’t like that.maybe use virtual machine is the best solution for me.

The benefits of using Virtual Machine

  • If you are newbie,Don’t worried about the crush of real server.Do everything you want even if Virtual Machine broken,we can fix it immediately through backup or snapshots
  • run Php script immediately without upload that is very convenient for debugging
  • you don’t buy a real server or cloud server only just for testing your php scripts

Blow is my steps for configuring Virtual Machine

  • Install Oracle VM virtualBox from here
  • Install Linux operate systems (e.g. Ubuntu,CentOS,RedHat……) they are siblings of each others(I choose the Ubuntu 14.04 as my server operate system)
  • Install Apache 2 server
  • the key step to mounting your file to Virtual Machine is that install virtualbox-guest-utils
sudo apt-get install virtualbox-guest-utils

Note:if virtualbox-guest-utils not be installed,”unknown filesystem type ‘vboxsf”” will be occurred.

  • Find “rc.local” file in /etc directory and add blow command in the file
mount -t vboxsf -o uid=1000,gid=1000 Name PATH

just like this:

VirtualBox_1

 

Name is the Folder Name in the virtual box,please checked Auto-mount and Make Permanent checkboxs. e.g.

VirtualBox_2

PATH is the “DocumentRoot”  in your Apache configuration file.
If you don’t familiar with DocummentRoot,please google it.

The last key step is make a network map during local machine and Virtual Machine.just like this:

 VirtualBox_3

Ok,All key steps we have already done,restart the Virtual Machine and any PHP script you write in windows can run immediately in window’s browsers.

If you have any questions or don’t understand any steps.Please tell me through the Email or comment 

 by the way, if shared directory is in mac and you want to set privileges. first set privileges in your mac.because mac have more priority than Linux,

 

  All rights reserved by Richard

 

programming \ php

remove index.php from the URL when uses the CI framework(apache)

 I used CI framework to write a website.(by the way CI framework is very useful ).I met a problem of how to  get rid of “index.php” from URL.maybe this is so easy for someone who was very skillful.but I post all my processes how to remove “index.php” from the URL.maybe it will help someone who isn’t very skillful just like me

Blow is a piece of documents from CI

“If your Apache server has mod_rewrite enabled, you can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except the specified items:”

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

 First of all,check whether or not we had enabled mod_rewrite.(if you don’t know how to check whether or not mod_rewrite is loaded,you will see rewrite.load in the directory of /etc/apache/mods-enabled/  and this is in the Ubuntu 14.04).The rewrite module is not the default configuration to Apache in the Ubuntu.

enable the rewrite module if you didn’t do it

sudo a2enmod rewrite

maybe need to restart your Apache Server

sudo service apache2 restart

 After that you will see a rewrite.load file in /etc/apache/mods-enabled/.

Now we have two ways to add the Apache directives to configuration file.

First,we can add it in global configuration file (e.g. apache.conf or httpd.conf) or Virtual Host context ( e.g. 000-default.conf).The differences between them is that Virtual Host context is only work in a relative Virtual Host , other’s virtual host will not work.

Add blow directives in your configuration file.

“the/directory/you/want/to/work” is the where the “index.php” stored.

<Directory the/directory/you/want/to/work >
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</Directory>

before we restart our Apache server,we should check the obvious syntax error in  our configuration file,

apche2ctl configtest

if you get the result of “Syntax OK“,then we can restart the server through blow command,else you have to correct the error that you made. 

 

Now we can see index.php is not necessary need occur in the URL:

Before we do,404 error occur in page 

CI_4

After add “index.php” in the URL,we get a response

CI_3

After we do,”index.php” is not necessarily any more

CI_2

programming

Magic methods in php

Athough I’m writing php almost a year,but still confused with magic methods.Now Today let me have a summary,

  • __construct() and __destruct()

    __construct() method is only invoked by create a instance,__destruct() method is only invoked by destroy a instance.so let me see a example:

<?php
class example
{
 private $foo=null;
 public function __construct($str){
 $this->foo = $str;
 echo "foo is ".$this->foo;
 }
 public function __destruct(){
 unset($this);
 echo "foo is unseted\n";
 }
}

$demo = new example('bar');

?>

运行的结果为:

foo is bar
foo is unseted
  • __call() and __callStatic()

__call() will be triggered by call inaccessible methods with object context.
__callStatic() will be triggered by call inaccessible methods with static context

for example:

<?php
class example{
 private static function private_m(){
 echo "this is private method\n";
 }
 protected static function protected_m(){
 echo "this is protected method\n";
 }
 public static function public_m(){
 echo "this is public method\n";
 }
public function __call($name,$args){
 echo $name." method you can't access\n";
 }
 public function __callStatic($name,$args){
 echo $name." method you can't access\n";
 }
}
$foo = new example;
$foo->private_m();
$foo->protected_m();
$foo->public_m();
example::private_m();
example::protected_m();
example::public_m();
?>

运行结果为:

private_m method you can't access
protected_m method you can't access
this is public method
private_m method you can't access
protected_m method you can't access
this is public method
  • __set() and __get()

__set() magic method is invoked by writing data to inaccessible properties

__get() magic method is invoked by reading data from inaccessible properties

举个例子:

<?php
class example
{
 private $foo='foo';
 protected $bar = 'bar';
 public $too = 'too';
 public function __set($name,$value)
 {
 echo $name." property can't change to ".$value."\n";
 }
 public function __get($name)
 {
 echo "can't get property of ".$name;
 }
}

$example = new example;
//test __get() magic method
echo $example->foo."\n";
echo $example->bar."\n";
echo $example->too."\n";
//test __set() magic method
$example->foo = 'foo is changed';
$example->bar = 'bar is changed';
$example->too = 'too is changed';

?>

运行结果为:

can't get property of foo
can't get property of bar
too
foo property can't change to foo is changed
bar property can't change to bar is changed
  • __isset() and __unset()

__isset() is triggered by invoking isset() or empty() method on inaccessible properties ,
__unset() is triggered by invoking unset() method on inaccessible properties

举个例子:

<?php
class example
{
 private $foo='foo';
 protected $bar = 'bar';
 public $too = 'too';
 public function __isset($name)
 {
 echo " can't access ".$name."\n";
 }
 public function __unset($name)
 {
 echo " can't unset ".$name."\n";
 }
}
$example = new example;

echo "is set 'not_exist' property ?";
isset($example->not_exist);
echo "is set 'foo' property ?";
isset($example->foo);
echo "is set 'bar' property ?";
isset($example->bar);
echo "is set 'too' property ?";
if(isset($example->too))
{
 echo "yes\n";
}else{
 echo "can't access too\n";
}
echo "is empty 'not_exist' property ?";
empty($example->not_exist);
echo "is empty 'foo' property ?";
empty($example->foo);
echo "is empty 'bar' property ?";
empty($example->bar);
echo "is empty 'too' property ?";
if(empty($example->too))
{
 echo "yes\n";
}else{
 echo "no empty \n";
}
unset($example->not_exist);
unset($example->foo);
unset($example->too);
?>

运行结果:

is set 'not_exist' property ? can't access not_exist
is set 'foo' property ? can't access foo
is set 'bar' property ? can't access bar
is set 'too' property ?yes
is empty 'not_exist' property ? can't access not_exist
is empty 'foo' property ? can't access foo
is empty 'bar' property ? can't access bar
is empty 'too' property ?no empty
 can't unset not_exist
 can't unset foo
  • __sleep() and __wakeup()

__sleep() is triggered by invoking serialize() method,
__wakeup() is triggered by invoking unserialized() method

举个例子:

<?php
class Connection
{
 protected $link;
 private $dsn, $username, $password;
public function __construct($dsn, $username, $password)
 {
 $this->dsn = $dsn;
 $this->username = $username;
 $this->password = $password;
 $this->connect();
 }
private function connect()
 {
 $this->link = new PDO($this->dsn, $this->username, $this->password);
 }
public function __sleep()
 {
 echo "__sleep() method is called\n";
 return array('dsn', 'username', 'password');
 }
public function __wakeup()
 {
 echo "__wakeup() method is called\n";
 $this->connect();
 }
}
$dsn = 'mysql:host=127.0.0.1;dbname=wordpress';
$username = 'joy';
$password = 'admin';
$con = new Connection($dsn,$username,$password);
$ser = serialize($con);
var_dump($ser);
$unser = unserialize($ser);
echo "\n";
var_dump($unser);
?>

运行结果:

__sleep() method is called
string(168) "O:10:"Connection":3:{s:15:"Connectiondsn";s:37:"mysql:host=127.0.0.1;dbname=wordpress";s:20:"Connectionusername";s:3:"joy";s:20:"Connectionpassword";s:5:"admin";}"
__wakeup() method is called

object(Connection)#3 (4) {
 ["link":protected]=>
 object(PDO)#4 (0) {
 }
 ["dsn":"Connection":private]=>
 string(37) "mysql:host=127.0.0.1;dbname=wordpress"
 ["username":"Connection":private]=>
 string(3) "joy"
 ["password":"Connection":private]=>
 string(5) "admin"
}
  • __toString() and __invoke()

__toString is triggered by put object as a string type data,such as echo  object,

__invoke is is triggered by use object as function,such as objec($params),

so this all simple,don’t need example,if you confused you can access php website

  • __set_state() and __debuginfo()

__set_state() is designed for var_export() function use.

__debuginfo() is designed for var_dump() function use

举个例子__set_state() magic mathod:

<?php
class A
{
 public $var1;
 public $var2;
public static function __set_state($an_array) // As of PHP 5.1.0
 {
 $obj = new A;
 $obj->var1 = $an_array['var1'];
 $obj->var2 = $an_array['var2'];
 return $obj;
 }
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
var_export($a);
echo "\n";
echo "eval take normal string to as code to excute\n";
eval('$b = ' . var_export($a, true) . ';');
var_dump($b);
?>

运行结果:

A::__set_state(array(
 'var1' => 5,
 'var2' => 'foo',
))
eval take normal string to as code to excute
object(A)#2 (2) {
 ["var1"]=>
 int(5)
 ["var2"]=>
 string(3) "foo"
}

__debuginfo()例子;

<?php
class C {
 private $prop;
public function __construct($val) {
 $this->prop = $val;
 }
public function __debugInfo() {
 return [
 'propSquared' => $this->prop ** 2,
 ];
 }
}
var_dump(new C(42));
?>

运行结果:

什么都没有,这是因为小蝙的php版本为5.5.9,至少要5.6才能运行。

programming

php exception处理小结

先看一段代码,你说echo “Not Executed\n”;会被执行吗?

<?php
 function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
return;
}
set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');
 echo "Not Executed\n";
 ?>

<?php
function inverse($x) {
 if (!$x) {
 throw new Exception('Division by zero.');
 }
 else return 1/$x;
 }
try {
 echo inverse(5) . "\n";
 echo inverse(0) . "\n";
 } catch (Exception $e) {
 echo 'Caught exception: ',  $e->getMessage(), "\n";
 }
// Continue execution
 echo 'Hello World';
 ?>