Saturday, October 14, 2017

Development speed - Ruby vs PHP

Hello, Readers!
As previously assured, i will write some interesting articles.
Today we are going to dispel a myth that Ruby is faster than PHP in term of development speed, learn curve and execution.

Firstly, i want to mention that Ruby is not any faster in term of development than PHP, just because native Ruby is almost the same as native PHP, except of various shortened command names, that might be confusing for new comers from other languages, but, they are completely okay once you are used to. ;-)
Most development speed related articles, let's we call them opinions - as they are, relates to RubyOnRails.
RubyOnRails is a framework, therefor i believe it is improper comparison of native PHP vs. foreign language's framework!
For above reason, i would like to really compare similar solutions in PHP and Ruby, we will take Symfony, you may compare it to Laravel, which is way easier than Symfony. Why we will compare these frameworks? Both are top languages' frameworks by popularity, both are used a lot on enterprise level.
Rails 5.1.14 vs Symfony 3.3

Application Initialization

Ruby:
ruby new app_name
PHP:
symfony new app_name

Conclusion: Tie! As you may noticed, same simple way...

API Application Initialization

Rails 5+
rails new app_name --api
Symfony 3.3+
composer create-project symfony/skeleton api

Conclusion: All the same. Few benefits to PHP when it comes to final outcome. Symfony Flex comes with all packages preconfigured which you can drop or add. Rails doesn't allow you to drop further any more than minimal installed.
Another Symfony advantage that controllers is completely optional in case of API, thank to API Platform that Symfony bases api on. Ruby will require creating models and controllers, defining routes and so on. For Symfony enough to scaffold model or create it manually, and CRUD will be available.
Additional advantage of Symfony, actually of API Platform, is that documentation automatically generated if you document models and methods according to swagger documentation. Inside documentation, also endpoints HTTP testing is generated.

Package Management

Both languages has fairly identical solutions. PHP has Composer and Ruby has Bundler.
Conclusion: Tie! Both are identical, exactly as app(not api) initialization was.

Tools

When it comes down to scaffolding, it is completely tie. Both frameworks provide identical options. Both will allow you scaffolding controllers, models, migrations, watch&debug defined routes, provide you with built-in debugging web server.
Conclusion: Tie!

Configuration and Settings

Databases: Both frameworks will require you to configure simple YAML file and provide you with various environments.
Packages: Packages configuration in rails(gems) will require from you, mostly to use initializers, luckily gems allow creator to state sample which will be moved to necessary project directory when developer uses special command. But, you'll have to deal with code. In Symfony, you will have to configure YAML, XML or INI (for you choice), but most packages with Symfony Flex will come pre-configured by default, all you will need is to adjust for your custom settings, if required. Similar to having default initializer.rb in rails.
Relations: In Rails relations are hard coded into Models. For each relation, you state the relation in both models. For example, if we have model X relates to model Y as one-to-many. You will define following way:
 
class X < ActiveModel do
  belongs_to: :Y
end

class Y < ActiveModel do
  has_many: :X
end
In Symfony, the best way is to configure relations using old and known XML.
Why XML? XML is very readable and is not afraid of loosing line-break as YAML, and Annotations that Symfony allows you too. Last is spreading configuration all over the system which is NOT GOOD AT ALL. Split configuration known to create messy code.
Routing: Routing in Symfony could also be done using YAML, XML or Annotations which is comments inside controllers. In Rails you will code similar configuration by coding into config/routes.rb.
Conclusion: Hard, but strongly, Symfony takes this with its solid and reliable configuration.

Architecture & Structure

Both frameworks allow you to go HMVC and do Anything you would like, however there is a few tricks.
Rails does not have clearly defined architecture to follow. Services you would create, you will probably instantiate directly or develop your own service locator and all belongings. On this note, Symfony has crazy advantage by having built-in service locator, solid configuration which allows various instantiation rules.
Database: When it comes down to database works, Ruby has Active Record and Symfony has fully featured ORM. Previous will quickly reveal its benefits and disadvantages under works with DB, as your DB load grows and you manipulate more data, it will be more noticed. Rails slows down amazingly, because every record retrieved being wrapped into a new instance of Model which in its turn will bring all the functionality coded in, inherited active record functionality, mixins, and so on. Which will cost you lots of memory and expensive run time. Symfony has advantage of using ORM, which relies on Entities, which is pretty clear classes that has setter and getters only, no inherited functionality and so on. This means that Symfony out of the box forces you to use Repositories or Interactors for manipulating data. In Rails you will have to break your head and (re-invent wheel?) most probably code PORO(plain old ruby object) which will have no inherited functionality and will speed up you application greatly, such development will cost your team a lot of time, as in additional you will need to switch queries to retrieve non standard data, then wrap it into PORO. Working with POROs will not be the same as previously used, so change existing code base to allow working with POROs. Yes, i did this in Rails... :)
Additional benefit due to ORM used, Symfony will make your code cleaner, as all the queries, etc. will be kept in Repositories. In Rails, queries will be kept in model and always be inherited to every record. If you switch to using POROs, you will probably go the Repositories way as well. Yes, did this in Rails as well.
Controllers: Technically, in Symfony you could not extend AbstractController or Controller at all and everything will work fine, as you are working with Response and Request objects, but you will not be able to access many helper methods provided by controller, and one of significant is accessing container.
Rails will bring all the base with him to controller, if you watch inheritance tree (it includes mixins as well) - 48(!) classes is mixed into one! 48!!! Waste of memory, sure, they was able to code it better way.
Conclusion: Symfony is a winner in this round by far. It provides stricter architecture, a lot better database management solution, cleaner code and less code overhaul.

I will stop here, maybe next time another extension to current article will arrive ;)

Conclusions:

All i can think, when one tells me that Rails' development speed faster than PHP is: Something inclines me that speaker probably never really developed PHP and Ruby on a professional level.
In my opinion, Rails could probably find home in small projects with 5-10 models and controllers, not much business logics and not highly load. If you will choose Rails for traffic intensive project, you'll face the ceiling and be forced to pay lots for servers or throwing lots into developments of modern/better architecture solutions just to save hundreds of bucks monthly.
The speed of development using Rails is not faster than Symfony, in best case - the same, the deeper you dive - the slower Rails development becomes.
One will not feel any difference during bootstraping the application using any of compared framework, but will face difficulties as proceeding deeper into the coding and architecture of the project, probably not that quick, in case of Rails, but sooner or later - expect it!
Lets talk slightly about learning curve. In my humble opinion, the learning curve for both is barely the same. PHP more readable, it is more like English and Ruby more like Chinese. Why Chinese? Because everything is shortened. Lets take an example of converting something to array. In PHP: (array)$var, in Rails: var.to_a
Don't take it close to heart, Rails' syntax is good and easy as PHP, but you will not really understand responsibility of a method by reading its name, as you would in PHP. Another misunderstood of developers when they face ->{} in Rails. Relax, it is just a lambda, you would write in PHP like function(){} to pass to any object. Easy, just learn it.

Thank You for visiting, specially if You managed to read till the end. I will really appreciate your opinions on subject. If you developed using both languages for at least a year+.

P.S. I have the right to compare these languages as i developed PHP for 6+ years and then gave a chance to Rails for nearly 2 years when i've done lots of interesting things and dated really great people, Thanks to RoomerTravel Ltd. for allowing me to go over from PHP to Rails for those 2 years.
Come more :P

Friday, October 13, 2017

5 Reasons Companies MUST consider upgrading to PHP7(at least)

Hello, Readers.
I am back to my blog since long time away. Now i have some free time, so i will make sure to add up interesting articles :-)
Following is AT LEAST 5 reasons that should convince you to upgrade.

1) Cut Expenses
Company will cut expenses by cutting down the memory usage, because PHP7 have implemented an optimized memory management when using lot of things, including, most usable - ARRAYS ! Lets take as an example generating 100,000 integers array and show the difference between PHP < 7 and PHP > 7.
$amount = 100000;
$beginMemory = memory_get_usage();
$array = [];
for ($i = 0; $i < $amount; $i++) {
   $array[$i] = $i;
}
$endMemory = memory_get_usage();
$memoryUsed = ceil(($endMemory - $beginMemory) / (1024*1024));
echo "memory = {$memoryUsed} MB";
In this case, depends on the machine, but mine is 64bit, so the result is following:
PHP5.6 - 14MB
PHP7 - 4MB


This argument, in my opinion, over weights any other reasons, so that i wrote it at first place.
May save companies hundreds of bucks in case application is memory intensive.
In case when developer chooses using SplFixedArray, this saving on expenses might reach X10 and even more.
If one, uses SplFixedArray for the code above, the overall memory consumption might reach as low as 2MB ! Feel the difference !

2) Easier hiring process
You would ask HOW? I will answer.
We are, as developers, usually tend to better/latest technologies, just because we understand that the old technology will leave us in the old world after for example 3 years. This leads us to think that after years working using old technologies, when we will back to job market - almost nobody will need us, because during recent years, most of companies have advanced, but we, as professionals, left behind and have to catch up...

3) Speed up your application
Literally like that. PHP7 out of the box is speeding up application by twice or triple of PHP5.6 on average.
As of writing this article, PHP7.1.10 is on market and 7.2 on its way as RC4 (next RC release on 26 October 2017 and final version will come very soon).

4) Improve code readability
PHP7 brought to us strict data typing, which bring us even more execution speeds and highly improved code readability.
Improved code readability will save development time, telling you as developer myself.

5) Security
PHP7 has better understanding that security matter and added new way algorithms to hash password and many more features that help solve security issues.

P.S. PHP 5.6 upgrading to PHP7 does not takes much, in case you don't have PHP4 mysql_* functions usage in code:) and you are not turning on strict data typing by default.
Enjoy the reading, and read more in google.
Also don't trust me wisely - benchmark youself first.

Wednesday, March 20, 2013

Native JavaScript | Remove DOM Element (easy!)

Hi, All.
If you'v been surfing my blog for a while, you may noticed that i am kindly a fun of simplifications and this article is not an exclusion from the rules. :)
Usually to remove an element, you need to perform quiet a few actions, as javascript gives you no easy way to do so.
I would like to explain and show how to easy remove DOM Element, don't forget to equip this function and add to your usable function list.
I also would really like if you still save the @author line, but i can forgive about it if you are really care for the code weight and minify the file.
A few actions to take before you remove is to find element, then traverse back to parent then from parent remove it's child. a complete mess - here it is simplified. Let's we move to the function itself and see how does it work.
/**
 * Remove DOM Element easier
 *
 * @author Valentin Ruskevych
 * @since 30 Dec 2012
 * 
 * @example
 *  document.getElementById('a').remove();
 */
HTMLElement.prototype.remove=function(){
 if (this.parentNode)
  this.parentNode.removeChild(this);
};

Let we break the function line by line to purely understand what is going on here.
Line: 1-9: Comments
Line: 10 : Add a new method "remove" to HTMLElement's prototype.
HTMLElement is a object that most page's elements inherits. If you know DOM Model, you probably know it.
Line: 11 : Ensure that the element we want to remove is having parent element by this.parentNode.
this - where comes from? this is belongs to context, and points to element that we called remove on.
example - document.getElementById('submit_button').remove(); - this points on element #submit_button
Line: 12 : finding parent of the element remove() called on, then remove it's child and pass "this" to the removeChild, so that making possible to remove parents child that is element we called remove on. a bit tricky, but, it is javascript :))

Hope i helped you to simplify/solve another problem :)

Sincerely,
VR

Native JavaScript Trim String Function (best performance)

Hi, All.

As we may already notice, sometimes we meet functionality requirements on page, app or extension that is quiet short and simple. There is no taste to load JavaScript Libraries such as jQuery, Prototype, ExtJS or any other. But using native JS made difficult for developers who only experienced with libraries, nowadays is a new trend.
Developer may tell you that he knows javascript, but reality proves that he only knows how to work with jquery and that is the end of his javascript knowledge.
My opinion, if coder tells you that he knows javascript - he must know it's internals.

Native javascript function TRIM to trim strings:

The trim function i'v coded is based on Steven Leviathan's researches and benchmarks of trimming methods.
Under these circumstances, i am not really developed it, but wrapped into a default String object's prototype to allow simpler use of string trimming function.
Take a look at the function, after the function is an example.
/**
 * Trim string method (regex way), based on Steven Levithan researches.
 *      Fastest triming on short strings, different aproach must be used for documents triming.
 * @author Rusevych Valentin
 * @since 16 Dec 2012
 * @return string trimmed.
 */
if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // fastest method (~8.5ms per 1000 iterations)
    }
}

/**
 * Usage Example
 **/
var s = '  TestString ';
s.trim();
console.log(s);
// output "TestString"


Take it into your file of "usable" functionality.
Sincerely,
VR

Thursday, March 7, 2013

JavaScript - Detect Quirks Mode state in visitor's browser

Hi, All.

Q: Quirks Mode breaks my front-end. Is it possible to detect Quirks Mode state on visitor? A: Yes, Possible. I will show it off right now.

Now much developers knows about javascript properties, only the discovers or the ones with reach experience.
JavaScripts stores inside it's object, all about page(document).
Document has a lot of interesting information, one of these we will take a look at called "compatMode".
// My Detecting method.
var quirks = false;
(function(){
   if(document.compatMode == 'BackCompat'){
      quirks = true;
   }
}())
Why this way? Only quirks mode making troubles. compatMode will have BackCompat value whenever Quirks Mode is on in browser. This making possible to detect any browser with Quirks Mode and perform your DOM/Data manipulations to satisfy the visitor experience. Have fun. Good Luck!

Wednesday, November 7, 2012

PHP Accessing array performance test / benchmark

Hi, All
Today we are going to benchmark array access, the key stored in variable, double quoted and single. Let we go, as usual, we go short and simple! As usual we run 1 million times.

Test Stand:
Hardware:
Intel i7 860 @ 2.8Ghz
Asus P7H55-M PRO
8GB DDR @ 1600Mhz Timings 8-8-8-24
SSD 80GB Intel SA2M080

Software
Windows 7 x64
Apache 2.2.17 (x86)
PHP 5.3.5

Let's begin.

Our test script looks such simple as:
set_time_limit(0);
$time_start = microtime(true);

$arr = array('name'=>'vasya', 'last_name'=>'patrik');
$tmp = NULL;
$i = 0;
while($i < 1000000){
    $tmp = NULL;
    $tmp = $arr["name"]; // different access method
    ++$i;
}
echo number_format(microtime(true)-$time_start, 6, '.', '').' seconds';

First we will run with double quotes. We will use $tmp = $arr["name"].
The results will be quiet interesting, and, as usual we calculate avg time for 10 runs.
First Case: $tmp = $arr["name"]
Result: 0.1790sec.

Second Case: $tmp = $arr['name']
Result: 0.1763sec.

Third Case: $tmp = $arr[$key]
Result: 0.1832sec.

Fourth Case: $tmp = $arr[0](after array refined to use int keys)
Result: 0.1659sec.

PHP Accessing array alternatives benchmark / performance test conclusion:
By the test results you can see that accessing array almost doesn't make sens from performance point of view, as we can see for 1 million assignments of $arr[key] to $tmp the coded runes very quick, 0.16-0.18s. Although makes sens, the fastest way of accessing is by integer key, as not surprisingly accessing array with a key stored in variable the slowest way. Just remember to use int keys whenever is possible, as this way will speed up the execution time of the code.

Sincerely,
Ruskevych Valentin

PHP echo vs print vs printf Performance test / Benchmark / Alternatives

Hi, All
Today we going to test the performance of php's functions: echo versus print versus printf. The test stand as usual, my workstation:)
The test will run 1 million of outputs.

Test Stand:
Hardware:
Intel i7 860 @ 2.8Ghz
Asus P7H55-M PRO
8GB DDR @ 1600Mhz Timings 8-8-8-24
SSD 80GB Intel SA2M080

Software
Windows 7 x64
Apache 2.2.17 (x86)
PHP 5.3.5

Let's begin.

Our test script looks such simple as:
set_time_limit(0);
$time_start = microtime(true);

$i=0;
while($i < 1000000){
    // initial command, whether echo, print of print_r
    ++$i;
}

echo number_format(microtime(true)-$time_start, 6, '.', ''),' seconds \n';

PHP Echo vs Print vs Printf Benchmark results:

* Note: Remember, tests timings are calculated as average based on 10 runs.
Output of string '1' single quoted and double quoted:
echo : Single quotes: 0.111sec. (Double quotes: 0.112sec. )
print : Single quotes: 0.120sec. (Double quotes: 0.120sec. )
printf : Single quotes: 0.468sec. (Double quotes: 0.468sec. )
In the case of sting w/o concatenation, variables, etc. the echo is fastest, while printf is slowest. Also as we can notice the double quotes makes a little difference in execution times. Lets proceed to a bit more complicated benchmarks.

This time we will output 1 character stored in variable for 1 million times, let's see whether we will have the difference.
echo : 0.117sec.
print : 0.128sec.
printf : 0.400sec.
The execution time are growing up, as expected, but printf shown increased performance towards the competitors. Anyways print_r stays slowest option of three.

Case: 'string'.$static_var.'string'.
*Note: static var i assume is 'z', not $i that changes every loop as in next test case.
echo : Single quoted: 0.282sec (Double quoted: 0.261sec )
print : Single quoted: 0.298sec (Double quoted: 0.274sec )
printf : Single quoted: 0.605sec (Double quoted: 0.547sec )
Seems very interesting:) No matter which scenario, the echo is fastest yet.

Next test case will perform string concatenation of three string in a way 'string'.var.'string' (using dots), the var is dynamic variable $i.
In case of printf used %s.
echo : single quoted: 0.481sec. (Double quoted: 0.483sec)
print : single quoted: 0.492sec. (Double quoted: 0.492sec)
printf : single quoted: 0.879sec (Double quoted: 0.879sec)
Conclusion: The echo is fastest yet, while printf is slowest. let's proceed testing other methods.

Next test case is output with commas. ',' rather than concatenating.
Static variable, assumes not changes every loop. Always the same. echo : Single quoted: 0.216sec (Double quoted: 0.243sec)
print : DOESN'T SUPPORT
printf : Single quoted: 0.534sec (Double quoted: 0.572sec)

PHP echo vs. print vs. printf performance/benchmark conclusions:
The conclusion is anyhow the echo is always faster, so preferred way to output data, also you may notice that using single quotes makes the execution a little, but faster. So take it to your coding standard and go with echo and single quotes.

Sincerely,
Valentin Ruskevych

Sunday, November 4, 2012

PHP Switch vs In_Array vs IsSet, Performance test / Alternatives / Benchmark

Hi, All :)
Today I just made a benchmark of PHP's Alternatives of looking up in array with ~30 keys and is around 60 keys. Not that big, but, that is the one i was needed to test for the work ;-)

Test Stand:
Hardware:
Intel i7 860 @ 2.8Ghz
Asus P7H55-M PRO
8GB DDR @ 1600Mhz Timings 8-8-8-24
SSD 80GB Intel SA2M080

Software
Windows 7 x64
Apache 2.2.17 (x86)
PHP 5.3.5

Let's begin.

The goal: Find language and locale by country in predefined values.
Starting point: The switch is used there by one of previous developers.

Test case php's Switch:
set_time_limit(0);
$time_start = microtime(true);
$country='ve';


$iterations = 1000000;
$i=0;
while($i<$iterations){
    $property ='';
    $lang='';
    $locale='';
    switch ($country) {
            case 'ar': $property .= 'ar';  $lang = 'es';  $locale = 'ar';  break; 
            case 'au': $property .= 'au';  $lang = 'en';  $locale = 'au';  break; 
            case 'br': $property .= 'br';  $lang = 'pt-BR'; $locale = 'br';  break; 
            case 'ca': $property .= 'ca';  $lang = 'en';  $locale = 'ca';  break; 
            case 'co': $property .= 'co';  $lang = 'es';  $locale = 'co';  break; 
            case 'fr': $property .= 'fr';  $lang = 'fr';  $locale = 'fr';  break; 
            case 'de': $property .= 'de';  $lang = 'de';  $locale = 'de';  break; 
            case 'hu': $property .= 'hu';  $lang = 'hu';  $locale = 'hu';  break; 
            case 'il': $property .= 'il';  $lang = 'he';  $locale = 'il';  break; 
            case 'it': $property .= 'it';  $lang = 'it';  $locale = 'it';  break; 
            case 'mx': $property .= 'mx';  $lang = 'es';  $locale = 'mx';  break; 
            case 'nl': $property .= 'nl';  $lang = 'nl';  $locale = 'nl';  break; 
            case 'no': $property .= 'no';  $lang = 'no';  $locale = 'no';  break; 
            case 'pt': $property .= 'pt';  $lang = 'pt-PT'; $locale = 'pt';  break; 
            case 'sa': $property .= 'sa';  $lang = 'ar';  $locale = 'sa';  break; 
            case 'za': $property .= 'za';  $lang = null;  $locale = 'za';  break; 
            case 'es': $property .= 'es';  $lang = 'es';  $locale = 'es';  break; 
            case 'se': $property .= 'se';  $lang = 'sv';  $locale = 'se';  break; 
            case 'ch': $property .= 'ch';  $lang = null;  $locale = 'ch';  break; 
            case 'th': $property .= 'th';  $lang = 'th';  $locale = 'th';  break; 
            case 'tr': $property .= 'tr';  $lang = 'tr';  $locale = 'tr';  break; 
            case 'ae': $property .= 'ae';  $lang = 'ar';  $locale = 'ae';  break; 
            case 'gb':
            case 'uk': $property .= 'uk';     $locale = 'uk';  break; 
            case 'us': $property .= 'us';        break; 
            case 've': $property .= 've';  $lang = 'es';  $locale = 've';  break; 
            default: $property .= 'row';     $locale = $country; break; 
    }
    ++$i;
}
$time_end = microtime(true);
echo number_format($time_end-$time_start, 6, '.', '')." seconds - switch 26 options\n";

Test case for php's In_array:
set_time_limit(0);
$time_start = microtime(true);
$country='ve';

$arr = array(
    'ar'=>array('property'=>'ar','lang'=>'es','locale'=>'ar')
    ,'au'=>array('property'=>'au','lang'=>'en','locale'=>'au')
    ,'br'=>array('property'=>'br','lang'=>'pt-BR','locale'=>'br')
    ,'ca'=>array('property'=>'ca','lang'=>'en','locale'=>'ca')
    ,'co'=>array('property'=>'co','lang'=>'es','locale'=>'co')
    ,'fr'=>array('property'=>'fr','lang'=>'fr','locale'=>'fr')
    ,'de'=>array('property'=>'de','lang'=>'de','locale'=>'de')
    ,'hu'=>array('property'=>'hu','lang'=>'hu','locale'=>'hu')
    ,'il'=>array('property'=>'il','lang'=>'he','locale'=>'il')
    ,'it'=>array('property'=>'it','lang'=>'it','locale'=>'it')
    ,'mx'=>array('property'=>'mx','lang'=>'es','locale'=>'mx')
    ,'nl'=>array('property'=>'nl','lang'=>'nl','locale'=>'nl')
    ,'no'=>array('property'=>'no','lang'=>'no','locale'=>'no')
    ,'pt'=>array('property'=>'pt','lang'=>'pt-PT','locale'=>'pt')
    ,'sa'=>array('property'=>'sa','lang'=>'ar','locale'=>'sa')
    ,'za'=>array('property'=>'za','lang'=>NULL,'locale'=>'za')
    ,'es'=>array('property'=>'es','lang'=>'es','locale'=>'es')
    ,'se'=>array('property'=>'se','lang'=>'sv','locale'=>'se')
    ,'ch'=>array('property'=>'ch','lang'=>NULL,'locale'=>'ch')
    ,'th'=>array('property'=>'th','lang'=>'th','locale'=>'th')
    ,'tr'=>array('property'=>'tr','lang'=>'tr','locale'=>'tr')
    ,'ae'=>array('property'=>'ae','lang'=>'ar','locale'=>'ae')
    ,'gb'=>array('property'=>'gb','lang'=>'en','locale'=>'uk')
    ,'uk'=>array('property'=>'uk','lang'=>'en','locale'=>'uk')
    ,'us'=>array('property'=>'us','lang'=>'en','locale'=>'us')
    ,'ve'=>array('property'=>'ve','lang'=>'es','locale'=>'ve')
);

$iterations = 1000000;
$i=0;
while($i<$iterations){
    $property ='';
    $lang='';
    $locale='';
    if(in_array($country, $arr) !== FALSE){
        $property = $arr[$country]['property'];
        $lang = $arr[$country]['lang'];
        $locale = $arr[$country]['locale'];
    }else{
        $property = 'row';
        $lang = 'en';
        $locale = $country;
    }
    ++$i;
}
$time_end = microtime(true);
echo number_format($time_end-$time_start, 6, '.', '')." seconds - in_array 26 options \n";

Test case for PHP's IsSet:
set_time_limit(0);
$time_start = microtime(true);
$country='ve';

$arr = array(
    'ar'=>array('property'=>'ar','lang'=>'es','locale'=>'ar')
    ,'au'=>array('property'=>'au','lang'=>'en','locale'=>'au')
    ,'br'=>array('property'=>'br','lang'=>'pt-BR','locale'=>'br')
    ,'ca'=>array('property'=>'ca','lang'=>'en','locale'=>'ca')
    ,'co'=>array('property'=>'co','lang'=>'es','locale'=>'co')
    ,'fr'=>array('property'=>'fr','lang'=>'fr','locale'=>'fr')
    ,'de'=>array('property'=>'de','lang'=>'de','locale'=>'de')
    ,'hu'=>array('property'=>'hu','lang'=>'hu','locale'=>'hu')
    ,'il'=>array('property'=>'il','lang'=>'he','locale'=>'il')
    ,'it'=>array('property'=>'it','lang'=>'it','locale'=>'it')
    ,'mx'=>array('property'=>'mx','lang'=>'es','locale'=>'mx')
    ,'nl'=>array('property'=>'nl','lang'=>'nl','locale'=>'nl')
    ,'no'=>array('property'=>'no','lang'=>'no','locale'=>'no')
    ,'pt'=>array('property'=>'pt','lang'=>'pt-PT','locale'=>'pt')
    ,'sa'=>array('property'=>'sa','lang'=>'ar','locale'=>'sa')
    ,'za'=>array('property'=>'za','lang'=>NULL,'locale'=>'za')
    ,'es'=>array('property'=>'es','lang'=>'es','locale'=>'es')
    ,'se'=>array('property'=>'se','lang'=>'sv','locale'=>'se')
    ,'ch'=>array('property'=>'ch','lang'=>NULL,'locale'=>'ch')
    ,'th'=>array('property'=>'th','lang'=>'th','locale'=>'th')
    ,'tr'=>array('property'=>'tr','lang'=>'tr','locale'=>'tr')
    ,'ae'=>array('property'=>'ae','lang'=>'ar','locale'=>'ae')
    ,'gb'=>array('property'=>'gb','lang'=>'en','locale'=>'uk')
    ,'uk'=>array('property'=>'uk','lang'=>'en','locale'=>'uk')
    ,'us'=>array('property'=>'us','lang'=>'en','locale'=>'us')
    ,'ve'=>array('property'=>'ve','lang'=>'es','locale'=>'ve')
);

$iterations = 1000000;
$i=0;
while($i<$iterations){
    $property ='';
    $lang='';
    $locale='';
    if(isset($arr[$country])){
        $property = $arr[$country]['property'];
        $lang = $arr[$country]['lang'];
        $locale = $arr[$country]['locale'];
    }else{
        $property = 'row';
        $lang = 'en';
        $locale = $country;
    }
    ++$i;
}
$time_end = microtime(true);
echo number_format($time_end-$time_start, 6, '.', '')." seconds - isset 26 options array \n";


To tell you the truth i was waited for In_Array to be slower than switch :), but let's take a look at the benchmark results.
PHP's Switch vs In_Array vs IsSet Benchmark Results:
*Notes:
The runs are (loop) 1 Million times
The time is counted as average for 10 runs * 1 million loops.
The time surrounded by closures is the time for the same run, but with *2 amount of keys in arrays.

The times
The key is set to last key in array
----------------------
For the Switch took: 2.094s. (3.726s)
For the In_Array took: 1.617s. (2.414s)
For the IsSet took: 0.848s. (0.899s.)
----------------------

The match is set to first key in array case:
----------------------
For the Switch: 0.569s. (0.629s) (great speed increase).
For the In_Array: 1.617s. (2.425s) (the execution still unchanged).
For the IsSet: 0.860s. (0.897s) (same with isset).
----------------------

No Match Case:
----------------------
For the Switch: 2.032s.(3.509s) (faster than last match. LOL)
For the In_Array: 1.657s. (2.372s) (Time almost not changing here)
For the IsSet: 0.540s. (0.507s) (Great increase!)
----------------------

Conclusion:
The best way to find whether the key is set in array is to use IsSet php's function.
As we see by the tests, Switch can bring performance only in case the key one of the first, the in_array in any case scanning array to the end and isset is as fast as lightning and becomes even faster when no match is found !
Also please note, as the amount of cases and array keys will become bigger, the switch and in_array will become slower, while isset doesn't have such issue.

The code isset($arr[$country]) brought to us best results.
Have fun playing around.

Sincerely,
Ruskevych Valentin

Tuesday, October 2, 2012

JQuery get field's default value (defaultValue) HOW-TO

Hi, Readers :)
If you got here, probably you already tried to reach field's defaultValue with jQuery and had no success.
Fine, i will show how to retrieve field's default value.
It is pretty easy to reach it.
I am showing real world example, the field that has "Search phrase..." and on focus have to be cleared, on blur have to return "search phrase..." if field is still blank.
 $('#widget_form_search #search_fld').live('focus', function(){
  if($(this)[0].defaultValue == $(this).val()){
   $(this).val('');
  }
 });
 $('#widget_form_search #search_fld').live('blur', function(){
  if('' == $(this).val()){
   $(this).val($(this)[0].defaultValue);
  }
 });

As you may see, accessing defaultValue is pretty easy
var defVal = $('#field_selector')[0].defaultValue;
Have fun:-)
Sincerely,
Ruskevych Valentin

Thursday, July 26, 2012

JavaScript HOW TO Verify Function exists in class

Hi, Readers.
Today i will explain how to verify in javascript whether the function/method and property/variable exists in class/object. Continue reading and i will teach how to...

The example(1) class we will work on is:
// class constructor
function Car(color){
   this.color = color;
   this.paint = function(color){
      this.color=color;
   };
}

The Example(2)
var Car = function(color){
   this.color = color;
};

Car.prototype.paint = function(color){
   this.color=color;
};

How to verify if property/variable or function/method exists in class/object in javascript?
for example(1), when function is defined as anonymous, we can use:
var c = new Car('red');
console.assert(true === c.hasOwnProperty('paint'), 'Doesnt exists');
// If you don't receive the 'Doesnt exists' in console, then the method/variable 
// is found, otherwise you will receive "Assertion failed: Doesnt exists"


On example(2) instance we should use a bit different construction.
Lookup in base object (not instance) On example(2) instance we should use a bit different construction.
Lookup in instantiated object
// lets see
c = new Car('red'); // instance
c.paint('blue');
alert(c.color); // alerts 'blue'

console.assert(true === c.hasOwnProperty('paint'), 'Doesnt exists');
console.assert(true === Car.prototype.hasOwnProperty('paint'));


Lookup for method/variable inside instantiated object in javascript
// lets see
c = new Car('red'); // instance
c.paint('blue');
alert(c.color); // alerts 'blue'

//previous try
console.assert(true === c.hasOwnProperty('paint'), 'Doesnt exists');
// new try
console.assert(true === c.__proto__.hasOwnProperty('paint'), 'Doesnt exists');

Why using __proto__ and what is exactly __proto__?
__proto__ is a "secret" reference to creator.

You can notice, that behavior of the method "paint" is as usual class method, it is painted our car to blue, but couldn't be found in class. Interesting?
This happens because it is defined with prototype and it is method of class' prototype that is also object.:)
The structure of the object Car
object Car
   property color
   object prototype/__proto__
      method paint

That is the prototype's behavior.
We will take a deeper look on prototypes and assertion in next articles.

Sincerely, Ruskevych Valentin