Tuesday, September 11, 2012

Jquery Tutorial | Jquery Selectors | Jquery filters

JQuery Questions 

1) What is jQuery Selectors? Give some examples.

jQuery Selectors are used to select one or a group of HTML elements from your web page.
jQuery support all the CSS selectors as well as many additional custom selectors.
jQuery selectors always start with dollar sign and parentheses: $()
There are three building blocks to select the elements in a web document.
1) Select elements by tag name

Example: $(div)
It will select all the div elements in the document.

2) Select elements by ID

Example: $(#xyzid”)
It will select single element that has an ID of xyzid

3) Select elements by class
Example: $(“.xyzclass”)
It will select all the elements having class xyzclass

2) How can we give face effect in jQuery?

In jQuery we have three methods to give the fade effect to elements: fadeIn, fadeOut and fadeTo
This methods change the opacity of element with animation.
Syntax:

$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)

“speed” can be one of following values : “slow”, “fast”, “normal” or milliseconds
“opacity” specify the value that allows the fading to given opacity.
“callback” is the function which we want to run once the fading effect is complete.
For example

$("clickme").click(function(){
$("mydiv").fadeTo("slow",0.50);
});

$("clickme").click(function(){
$("mydiv").fadeOut(3000);
});.

3) Explain the animate function.

-The animate function is used to apply the custom animation effect to elements.

-Syntax:

$(selector).animate({params}, [duration], [easing], [callback])

“param” defines the CSS properties on which you want to apply the animation.
“duration” specify how long the animation will run. It can be one of following values : “slow”, “fast”, “normal” or milliseconds
“easing” is the string which specify the function for the transition.
“callback” is the function which we want to run once the animation effect is complete.
For example

Click Me
Following is the jQuery to animate opacity, left offset, and height of the mydiv element $('# clickToAnimate’).click(function() { $('#book').animate({ opacity: 0.30, left: '+=20', height: 'toggle' }, 3000, function() { // run after the animation complete. }); }); 4) What is .siblings() method in jQuery? When we want to fetch siblings of every elements in the set of matched elements then we can use siblings() method. We filter the elements fetched by an optional selector. Syntax : .siblings( [selector]) “selector” is the selector expression which specify the matched elements. For example
  • item 1
  • item 2
  • item 3
  • item 4
Now we want to find the siblings of the element of id “second_item” and change the text color to Blue : $(‘li.second_item’).siblings().css(‘color’,’blue’); If we want specific sibling elements for example the elements having class “myitem” then we can pass a optional selector: $(‘li.second_item’).siblings(‘.myitem’).css(‘color’,’blue’); 5) Explain width() vs css(‘width’). In jQuery, there are two way to change the width of an element. One way is using .css(‘width’) and other way is using .width(). For example $(‘#mydiv’).css(‘width’,’300px’); $(‘#mydiv’).width(100); The difference in .css(‘width’) and .width() is the data type of value we specify or return from the both functions. In .css(‘width’) we have to add “px” in the width value while in .width() we don’t have to add. When you want to get the width of “mydiv” element then .css(‘width’) will return ‘300px’ while .width() will return only integer value 300. 6) What is the use of jQuery.data()? jQuery.data() is used to set/return arbitrary data to/from an element. Syntax: jQuery.data(element, key, value) “element” is the DOM element to which the data is associated. “key” is an arbitrary name of the piece of data. “value” is value of the specified key. Suppose we want to set the data for a span element: jQuery.data(span, “item”, { val1: 10, val2: "myitem" }); If we want to retrieve the data related to div element and set it to label’s data: $("label:val1").text(jQuery.data(div, "item").val1); $("label:val2").text(jQuery.data(div, "item").val2); 7) Explain bind() vs live() vs delegate() methods. -The bind() method will not attach events to those elements which are added after DOM is loaded while live() and delegate() methods attach events to the future elements also. -The difference between live() and delegate() methods is live() function will not work in chaining. It will work only on an selector or an element while delegate() method can work in chaining. For example $(document).ready(function(){ $("#myTable").find("tr").live("click",function(){ alert($(this).text()); }); }); Above code will not work using live() method. But using delegate() method we can accomplish this. $(document).ready(function(){ $("#dvContainer")children("table").delegate("tr","click",function(){ alert($(this).text()); }); }); 8) Explain the each() function. -The each() function specify the function to be called for every matched element. Syntax: $(selector).each(function (index, element)) “index” is the index position of the selector. “selector” specifies the current selector where we can use “this” selector also. In the case when we need to stop the each loop early then we can use “return false;” For example $("#clickme").click(function(){ $("li").each(function(){ document.write($(this).text()) }); }); This will write the text for each “li” element. 9) Explain slideToggle() effect. -slideToggle() effect is used to give animated sliding effect to an element. Syntax: slideToggle([ duration] [, easing] [, callback]) “duration” is the number specifying how long the animation will run. “easing” is the string which specify the function for the transition. “callback” is the function which we want to run once the animation is complete. If the element is visible then this effect will slide the element up side and make it completely hidden. If the element is hidden then slideToggle() effect will slide it down side and make it visible. We can specify the toggle speed with this effect. For example $("#clickme").click(function(){ $("#mydiv").slideToggle(“slow”, function(){ //run after the animation is complete. }); }); 10) What is difference between $(this) and ‘this’ in jQuery? Refer the following example $(document).ready(function(){ $(‘#clickme’).click(function(){ alert($(this).text()); alert(this.innerText); }); }); -this and $(this) references the same element but the difference is that “this” is used in traditional way but when “this” is used with $() then it becomes a jQuery object on which we can use the functions of jQuery. -In the example given, when only “this” keyword is used then we can use the jQuery text() function to get the text of the element, because it is not jQuery object. Once the “this” keyword is wrapped in $() then we can use the jQuery function text() to get the text of the element. 11) What is the use of param() method. The param() method is used to represent an array or an object in serialize manner. While making an ajax request we can use these serialize values in the query strings of URL. Syntax: $.param(object | array, boolValue) “object | array” specifies an array or an object to be serialized. “boolValue” specifies whether to use the traditional style of param serialization or not. For example: personObj=new Object(); empObject.name="Arpit"; empObject.age="24"; empObject.dept=”IT”; $("#clickme").click(function(){ $("span").text($.param(empObject)); }); It will set the text of span to “name=Arpit&age=24&dep=IT” 12) What is jQuery.holdReady() function? -By using jQuery.holdReady() function we can hold or release the execution of jQuery’s ready event. -This method should be call before we run ready event. -To delay the ready event, we have to call jQuery.holdReady(true); -When we want to release the ready event then we have to call jQuery.holdReady(false); -This function is helpful when we want to load any jQuery plugins before the execution of ready event. For example $.holdReady(true); $.getScript("xyzplugin.js", function() { $.holdReady(false); }); 13) Explain .empty() vs .remove() vs .detach(). -.empty() method is used to remove all the child elements from matched elements. -.remove() method is used to remove all the matched element. This method will remove all the jQuery data associated with the matched element. -.detach() method is same as .remove() method except that the .detach() method doesn’t remove jQuery data associated with the matched elements. -.remove() is faster than .empty() or .detach() method. Syntax: $(selector).empty(); $(selector).remove(); $(selector).detach(); 14) How to read, write and delete cookies in jQuery? -To deal with cookies in jQuery we have to use the Dough cookie plugin. -Dough is easy to use and having powerful features. -Create cookie $.dough("cookie_name", "cookie_value"); Read Cookie $.dough("cookie_name"); Delete cookie $.dough("cookie_name", "remove"); 15) Is window.onload is different from document.ready()? - The window.onload() is Java script function and document.ready() is jQuery event which are called when page is loaded. - The difference is that document.ready() is called after the DOM is loaded without waiting for all the contents to get loaded. While window.onload() function waits until the contents of page is loaded. - Suppose there is very large image on a page, at that time window.onload() will wait until that image is loaded totally. - So while using the window.onlaod() function the execution will be slow, but the document.ready() will not wait until the image is loaded. 16) What is Chaining in jQuery? - Chaining is very powerful feature of jQuery. - Chaining means specifying multiple function and/or selectors to an element. - Examine the below example $(document).ready(function(){ $('#mydiv').css('color', 'blue'); $('#mydiv').addClass('myclass'); $('#mydiv').fadeIn('fast'); } By using chaining we can write above code as follows $(document).ready(function(){ $('#mydiv').css('color', 'blue').addClass('myclass').fadeIn('fast'); }); -Advantage of chaining is that it makes your code simple and simple to manage. -The execution becomes faster because the code search for the element only once. 17) What is difference between sorting string array and sorting numerical array in jQuery? The sort method is used to sort any array elements. It sorts the string elements alphabetically. For example $(document).ready(function(){ var mylist = [ “Apple”,”Orange”,”Banana”]; mylist = mylist.sort(); $(“#mydiv”).html(list.join(“”)); }); It will give following output Apple Banana Orange Now we declare a numerical array and use sort() method to sort its elements. $(document).ready(function(){ var mylist = [ “20”,”3””100”,”50”]; mylist = mylist.sort(); $(“#mydiv”).html(list.join(“”)); }); It will give following output 100 20 3 50 18) What is difference between prop and attr? In jQuery both prop() and attr() function is used to set/get the value of specified property of an element. The difference in both the function is that attr() returns the default value of the property while the prop() returns the current value of the property. For example $('input').prop('value', 'Changed Value'); -.attr('value') will return 'My Value' -.prop('value') will return 'Changed Value' 19) How to always reference latest version of jQuery? When you reference the jQuery on your web page, you have to specify the version number also. Above code will always load the 1.5.1 version of jQuery. If you reference the latest jQuery then you don’t need to change the code every time the new version of jQuery is released. To achieve this you have to use following code This code will always reference the latest version of jQuery in your page. 20) What is resize() function in jQuery? The resize() function is called whenever the browser size is changed. This event can be only used with $(window). Syntax: .resize([event_data], handler(event_object)) -The “event_data” is the data to be sent to the handler. -The “handler(event_object)” is a function to be called each time when the window is resized. For example $(window).resize(function() { $('#message).text('window is resized to ' + $(window).width() + ‘x’ + $(window).height()); });

Monday, September 10, 2012

Flex Profiling | Flex Memory Tunning | Flex Garbage Collection|Flex Performance Optimization |Flex Memory.

1) Why do we use Flex Profiling?
To find memory Leaks
To find excessive Allocation
to find long running process
to find excessively called process
2) Flex profiler doesnt report everything like
Doesnt Report Browser Memory
Doesnt Report Os Memory.
Memory used to display visuals
memory used to get events
memory used to handle network file access.
Memory used by the flash player
memory used by jit buffer.
Memory used by subobjects or strings.
3) System.total memory doesnt report everything either like
above points.
4) Whats new Flexbuilder4 Profiler
Improved object reference panel
shortest path from object to GC.

Viewing information in the Live Objects view

The Live Objects view displays information about the classes that the current application uses. This view shows which classes are instantiated, how many were created, how many are in memory, and how much memory the active objects are taking up.
The profiler updates the data in the Live Objects view continually while you profile the application. You do not have to refresh the view or keep focus on it to update the data.
The following table describes the columns in the Live Objects view:
Column
Description
ClassThe classes that have instances in the currently running application.
Package :The package that each class is in. If the class is not in a package, then the value of this field is the file name that the class is in. The number following the dollar sign is a unique ID for that class.
If the Package field is empty, the class is in the global package or the unnamed package.
Cumulative Instances : The total number of instances of each class that have been created since the application started.
Instances
The number of instances of each class that are currently in memory. This value is always smaller than or equal to the value in the Cumulative Instances column.
Cumulative Memory :The total amount of memory, in bytes, that all instances of each class used, including classes that are no longer in memory.
Memory :The total amount of memory, in bytes, that all instances of each class currently use. This value is always smaller than or equal to the value in the Cumulative Memory column.

Using the Memory Snapshot view
The Memory Snapshot view displays information about the application’s objects and memory usage at a particular time. Unlike the Live Objects view, the data in the Memory Snapshot view is not continually updated
Using the Object References view
The Object References view displays stack traces for classes that were instantiated in the application.
To open the Object References view, double-click a class name in the Memory Snapshot or Loitering Objects views. The Object References view displays information about the selected class’s instances.
The Object References view displays data in two tables: the Instances table and the Allocation Trace table.
Performance profiling:  is the process of looking for methods in your application that run slowly and can be improved. Once identified, these hot spots can be optimized to speed up execution times so that your application runs faster and responds more quickly to user interaction. You generally look for two things when doing performance profiling: a method that is called only once but takes more time to run than similar methods, or a method that may not take much time to run but is called many times. You use the performance profiling data to identify the methods that you then optimize. You might find that reducing the number of calls to a method is more effective than refactoring the code within the method.
Memory profiling : is the process of examining how much memory each object or type of object is using in the application. You use the memory profiling data in several ways: to see if there are objects that are larger than necessary, to see if there are too many objects of a single type, and to identify objects that are not garbage collected (memory leaks). By using the memory profiling data, you can try to reduce the size of objects, reduce the number of objects that are created, or allow objects to be garbage collected by removing references to them.
Memory profiling can slow performance of your application because it uses much more memory than performance profiling. You should only do memory profiling when necessary.

Using the Allocation Trace view
The Allocation Trace view shows which methods were called between two memory snapshots and how much memory was consumed during those method calls. To open the Allocation Trace view, you select two memory snapshots, and then click the View Allocation Trace button. For information on recording a memory snapshot.
The result of the memory snapshot comparison is a list of methods that Flash Player executed between the two memory snapshots. For each of these methods, the profiler reports the number of objects created in that method.

Using the Object Statistics view
The Object Statistics view shows the performance statistics of the selected group of objects. This view helps you identify which methods call a disproportionate number of other methods. It also shows you how much memory the objects instantiated in those method calls consume. You use the Object Statistics view to identify potential memory leaks and other sources of performance problems in your application.
Using the Performance Profile view
The Performance Profile view is the primary view to use when doing performance profiling. It shows statistics such as number of calls, self-time, and cumulative time for the methods that are called during a particular sampling interval. You use this data to identify performance bottlenecks.

Changing timeout length
When you test your application, be aware of the scriptTimeLimit property. If an application takes too long to initialize, Flash Player warns users that a script is causing Flash Player to run slowly and prompts the user to abort the application. If this is the situation, you can set the scriptTimeLimit property of the tag to a longer time so that the Flex application has enough time to initialize.
However, the default value of the scriptTimeLimit property is 60 seconds, which is also the maximum, so you can only increase the value if you have previously set it to a lower value. You rarely need to change this value.
The following example sets the scriptTimeLimit property to 30:

Flex Memory and GarbageCollector

When you use addEventListener() method and register a event listener to an object you create reference. By default any object that has a reference to a listener will keep that reference until it is removed using the removeEventListener() method. Strong references will not be cleaned up by Flash player GC and remain in memory until the application is closed or the world ends, whichever comes first. This makes for a horribly leaky AIR applications,

The ActionScript 3.0 garbage collector uses two methods for locating objects with no active references: reference counting and mark sweeping.

Reference counting : Reference Counting is quite good and easy with no overhead on CPU,But it has the problem with circular references So in over to eradicate this sort of situations there is another approach Mark and Sweep.

How to identify memory leaks in Flex Application
1) Create/Destroy
2)Replace Current

Use Additional Parameters of Listener
The addEventListener() method does have some additional (and seldom used) parameters to create a weak reference when adding the listener to an object. On of those parameters is “useWeakReference”, the 5th parameter of the method. To utilize this parameter you need to set it from false to true:
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean= false);
var button:Button = new Button()
button.addEventListener(MouseEvent.click, handleMouseClick, false, 0, true);

Preventing client-side caching

When you test performance, ensure that you are not serving files from the local cache to Flash Player. Otherwise, this can give false results about download times. Also, during development and testing, you might want to change aspects of the application such as embedded images, but the browser continues to use the old images from your cache.
If the date and time in the If-Modified-Since request header matches the date and time in the Last-Modified response header, the browser loads the SWF file from its cache. Then the server returns the 304 Not Modified message. If the Last-Modified header is more recent, the server returns the SWF file.
You can use the following techniques to disable client-side caching:
Delete the Flex files from the browser’s cache after each interaction with your application. Browsers typically store the SWF file and other remote assets in their cache. On Microsoft Internet Explorer in Windows XP, for example, you can delete all the files in c:\Documents and Settings\username\Local Settings\Temporary Internet Files to force a refresh of the files on the next request.

Set the HTTP headers for the SWF file request in the HTML wrapper to prevent caching of the SWF file on the client. The following example shows how to set headers that prevent caching in JSP:
// Set Cache-Control to no-cache.
response.setHeader(“Cache-Control”, “no-cache”);
// Prevent proxy caching.
response.setHeader(“Pragma”, “no-cache”);
// Set expiration date to a date in the past.
response.setDateHeader(“Expires”, 946080000000L); //Approx Jan 1, 2000
// Force always modified.
response.header(“Last-Modified”, new Date());

Reducing SWF file sizes

You can improve initial user experience by reducing the time it takes to start an application. Part of this time is determined by the download process, where the SWF file is returned from the server to the client. The smaller the SWF file, the shorter the download wait. In addition, reducing the size of the SWF file also results in a shorter application initialization time. Larger SWF files take longer to unpack in Flash Player.
The mxmlc compiler includes several options that can help reduce SWF file size.
Using the bytecode optimizer
The bytecode optimizer can reduce the size of the Flex application’s SWF file by using bytecode merging and peephole optimization. Peephole optimization removes redundant instructions from the bytecode.
If you are using Flex Builder or the mxmlc command-line compiler, you can set the optimize compiler option to true, as the following example shows:
mxmlc -optimize=true MyApp.mxml

Disabling debugging
Disabling debugging can make your SWF files smaller. When debugging is enabled, the Flex compilers include line numbers and other navigational information in the SWF file that are only used in a debugging environment. Disabling debugging reduces functionality of the fdb command-line debugger and the debugger built into Flex Builder.
To disable debugging, set the debug compiler option to false. The default value for the mxmlc compiler is false. The default value for the compc compiler is true.
For more information about debugging, see Using the Command-Line Debugger.
Using strict mode
When you set the strict compiler option to true, the compiler verifies that definitions and package names in import statements are used in the application. If the imported classes are not used, the compiler reports an error.
Externalizing assets
There are various methods of externalizing assets used by your Flex applications; these include:
Using modules
Using run-time stylesheets
Using Runtime Shared Libraries (RSLs)
Loading assets at run time rather than embedding them

Component libraries. 
Component libraries are SWC files that contain one or more components that are used by applications. SWC files also contain the namespace information that describe the contents of the SWC file. For more information about component libraries, see About SWC files.

Run-time shared libraries (RSLs). 
RSLs are external shared assets that can be separately downloaded and cached on the client. These shared assets are loaded by any number of applications at run time. For more information on RSLs, see Using Runtime Shared Libraries.

Themes. 
Themes are a combination of graphical and programmatic skins, and Cascading Style Sheets (CSS). You use themes to define the look and feel of a Flex application.
Comparing dynamic and static linking
Most large applications use libraries of ActionScript classes and components. You must decide whether to use static or dynamic linking when using these libraries in your Flex applications.

When you use static linking, the compiler includes all components, classes, and their dependencies in the application SWF file when you compile the application. The result is a larger SWF file that takes longer to download but loads and runs quickly because all the code is in the SWF file. To compile your application that uses libraries and to statically link those definitions into your application, you use the library-path and include-libraries options to specify the locations of SWC files.

Dynamic linking is when some classes used by an application are left in an external file that is loaded at run time. The result is a smaller SWF file size for the main application, but the application relies on external files that are loaded during run time.
To dynamically link classes and components, you compile a library. You then instruct the compiler to exclude that library’s contents from the application SWF file. You must still provide link-checking at compile time even though the classes are not going to be included in the final SWF file.
You use dynamic linking by creating component libraries and compiling them with your application by using the external-library-path, externs, or load-externs compiler options. These options instruct the compiler to exclude resources defined by their arguments from inclusion in the application, but to check links against them and prepare to load them at run time. The external-library-path option specifies SWC files or directories for dynamic linking.
Using RSLs to reduce SWF file size
One way to reduce the size of your application’s SWF file is by externalizing shared assets into stand-alone files that can be separately downloaded and cached on the client. These shared assets are loaded by any number of applications at run time, but must be transferred only once to the client. These shared files are known as Runtime Shared Libraries (RSLs).
If you have multiple applications but those applications share a core set of components or classes, your users will be required to download those assets only once as an RSL. The applications that share the assets in the RSL use the same cached RSL as the source for the libraries as long as they are in the same domain. The resulting file size for your applications can be reduced. The benefits increase as the number of applications that use the RSL increases.
When you create an RSL, be sure to optimize it prior to deployment. This removes debugging information as well as unnecessary metadata from the RSL, which can dramatically reduce its size.
Using styles
You use styles to define the look and feel of your Flex applications. You can use them to change the appearance of a single component, or apply them globally. Be aware that some methods of applying styles are more expensive than others. You can increase your application’s performance by changing the way you apply styles.
For more information about using styles, see Using Styles and Themes in the Adobe Flex 3 Developer Guide.
Loading stylesheets at run time
You can load stylesheets at run time by using the StyleManager. These style sheets take the form of SWF files that are dynamically loaded while your Flex application runs.
By loading style sheets at run time, you can load images (for graphical skins), fonts, type and class selectors, and programmatic skins into your Flex application without embedding them at compile time. This lets skins and fonts be partitioned into separate SWF files, away from the main application. As a result, the application’s SWF file size is smaller, which reduces the initial download time. However, the first time a run-time style sheet is used, it takes longer for the styles and skins to be applied because Flex must download the necessary CSS-based SWF file.
For more information, see the Adobe Flex 3 Developer Guide.
Reducing calls to the setStyle() method
Run-time cascading styles are very powerful, but use them sparingly and in the correct context. Calling the setStyle() method can be an expensive operation because the call requires notifying all the children of the newly-styled object. The resulting tree of children that must be notified can be quite large.
Using deferred creation
To improve the start-up time of your application, minimize the number of objects that are created when the application is first loaded. If a user-interface component is not initially visible at start up, create that component only when you need it. This is called deferred creation. Containers that have multiple views, such as an Accordion, provide built-in support for this behavior. You can use ActionScript to customize the creation order of multiple-view containers or defer the creation of other containers and controls.
To use deferred creation, you set the value of a component’s creationPolicy property to all, auto, or none.
Flex memory tuning tips

1. Memory Leaks caused by Event Listeners

Always remove unused event listeners. Each time an event listener is added to an object, it increases the object’s reference count. So the reference remains, until the event listener is removed. If for some reason, you cannot remove the event listener use the useWeakReference parameter in the addEventListener. This does not increase the reference count.

Problem:

When you call addEventListener() on the TextInput instance, it responds by adding a reference to the object (the one that contains the handleTextChanged method) to a list of objects that need to be notified when this event occurs. When it’s time to broadcast the change event, the TextInput instance loops through this list and notifies each object that registered as a listener. In terms of garbage collection, this means that, in certain circumstances, if an object is listening for events it may never be available for garbage collection.

The following example shows a simple case:

var textInput:TextInput = new TextInput();
textInput.addEventListener(‘change’, handleTextChanged);

Solution:

When adding an event listener to a broadcaster, the developer can specify that the event listener should use weak references. This is accomplished by specifying extra parameters for the addEventListener() method:

var textInput:TextInput = new TextInput();
textInput.addEventListener(‘change’, handleTextChanged, false, 0, true);

2. Using Item Renderer

Use item renderers judiciously. An item renderer derived from a Container class comes with lot of unnecessary overhead. Instead use a simpler class, may be an Actionscript class derived from a UIComponent. This would reduce a lot of overhead.

3. Using Images

Use images that are smaller in size and when they are large in number prefer not to embed them in the application. As far as the image formats are concerned, PNG images are much faster than other image types.

Use BitmapData as much as possible. Use dispose() method of BitmapData to free memory that is used to store the BitmapData object.

4. Bindings

Use Binding only when necessary. Data binding expressions usually take up memory. Prefer assignments to Binding whenever possible.

5. Variables

Accessing local variables is much faster. If you have variables that need to be accessed more use local variables as they are stored on the stack and accessing them is much faster.

You could help the garbage collector by assigning unused variables to null.

6. Instance Creation

For components use deferred instantiation. This would immensly reduce the startup time. Be wary of creationPolicy=”all”. Try to avoid removeChild() / addChild() when it would work just as well to reuse an object or just toggle the visible property.

7. Containers

Minimize the use of containers. Try not to nest HBoxes within VBoxes and so on. Nested containers make up to huge overheads.

8. Types Conversions

Use types for the variables. Avoid implicit type conversions and when unsure of the type use the “as” operator.

9. Repeaters

Repeaters have a property called recycleChildren.Set it to true. When set to true, the repeater reuses the children it already created instead of creating new ones.

10. Dictionary

Use weak references in the Dictionary object.

11. Modules

Don’t unnecessarily load/unload modules. If you need to unload a module, make sure to remove all references pointing to it. In particular if you have an event listener from within the module to something outside the module, that can prevent the module’s memory from being reclaimed.

12. NativeWindow

After making a NativeWindow you must call close() before it can be GC’ed. But you must remove references before you can call close(). Also when you open a FileStream object in asynchronous mode, pending event listeners can prevent the FileStream object from being GC’ed.

Sources:

http://www.peachpit.com/articles/article.aspx?p=1182473

http://www.adobe.com/devnet/flashplayer/articles/resource_management.html

2. Flex Performance Profiling

Performance profiling is used to find aspects of the flex application that are unresponsive, or where performance can be improved. When profiling for performance, generally one should be looking for methods that are executed very frequently, or methods that take a long time whenever they’re executed. The combination of those two factors usually provides a good indication of where your time should be spent in optimizing or potentially refactoring.

Using the Flex Builder 3 Profiler, one can identify the slowest portions of the application and optimize it. Flex Builder profiler allows one to take performance snapshots to record how long was spent in each function. This is useful to identify the areas of code that might benefit from optimization. While profiler is running everything is much slower. Often Mouse or similar Events will seem to take lots of time, you can ignore these. Investigate your own functions and see if they have been called too often or they take too long.

Flex Performance Tuning Tips

Flex Speed Tips: Matt chotin has shared a some great tips to improve Flex performance. Following are a few of them:

* If you have a type in AS3, which you are not sure of always use the As operator to cast the type before you use it. This avoids VM errors with try/catch, which slow the execution and is ten times slower than the As operator.

* Array is access is slow if the array is sparse. It may be faster to put nulls in empty values as this speeds things up. Array misses are very slow, up to 20 times slower than finding a valid entry.

* Avoid implicit type conversion. In the player it will convert integers to numbers and back when asked to add integers. You might as well use numbers for everything and convert back to integer at the end.

* Local variable access is faster, so assign variables to local if they are accessed a lot. They will be stored on the stack and access is much quicker.

* Data Binding expressions take up memory and can slow down the application startup. It may be more efficient to do an assignment in code rather than using binding.

* Find a slow computer and run your application. If it runs OK ship it! Other wise you can use flash.utils.getTimer():int to get a time value in miliseconds before and after some process to time it.

More information on tuning ActionScript can be found in Matt chotin’s article

http://www.adobe.com/devnet/flex/articles/as3_tuning.html

Sources:

http://www.peachpit.com/articles/article.aspx?p=1182473&seqNum=3

http://www.adobe.com/devnet/flex/articles/as3_tuning.html

 

Thanks,

Shyam.S

 


Different types of Hibernate Caches|How to configure Hibernate Cache| First Level Second Level Hibernate Cache | Custom Hibernate

1) Introduction
While working with Hibernate web applications we will face so many problems in its performance due to database traffic. That to when the database traffic is very heavy . Actually hibernate is well used just because of its high performance only. So some techniques are necessary to maintain its performance. Caching is the best technique to solve this problem. In this article we will discuss about, how we can improve the performance of Hibernate web applications using caching.
The performance of Hibernate web applications is improved using caching by optimizing the database applications. The cache actually stores the data already loaded from the database, so that the traffic between our application and the database will be reduced when the application want to access that data again. Maximum the application will works with the data in the cache only. Whenever some another data is needed, the database will be accessed. Because the time needed to access the database is more when compared with the time needed to access the cache. So obviously the access time and traffic will be reduced between the application and the database. Here the cache stores only the data related to current running application. In order to do that, the cache must be cleared time to time whenever the applications are changing. Here are the contents.
  • Introduction.
    • First-level cache.
    • Second-level cache.
  • Cache Implementations.
    • EHCache.
    • OSCache.
    • SwarmCache.
    • JBoss TreeCache.
  • Caching Stringategies.
    • Read-only.
    • Read-Write.
    • Nonstriict read-write.
    • Transactional.
  • Configuration.
  • <cache> element.
  • Caching the queries.
  • Custom Cache.
    • Configuration.
    • Implementation :: ExampleCustomCache.
  • Something about Caching.
    • Performance.
    • About Caching.
  • Conclusion.
Hibernate uses two different caches for objects: first-level cache and second-level cache..

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

2) Cache Implementations

Hibernate supports four open-source cache implementations named EHCache (Easy Hibernate Cache), OSCache (Open Symphony Cache), Swarm Cache, and JBoss Tree Cache. Each cache has different performance, memory use, and configuration possibilities.

2.1) 2.1 EHCache (Easy Hibernate Cache) (org.hibernate.cache.EhCacheProvider)

  • It is fast.
  • lightweight.
  • Easy-to-use.
  • Supports read-only and read/write caching.
  • Supports memory-based and disk-based caching.
  • Does not support clustering.

2.2)OSCache (Open Symphony Cache) (org.hibernate.cache.OSCacheProvider)

  • It is a powerful .
  • flexible package
  • supports read-only and read/write caching.
  • Supports memory- based and disk-based caching.
  • Provides basic support for clustering via either JavaGroups or JMS.

2.3)SwarmCache (org.hibernate.cache.SwarmCacheProvider)

  • is a cluster-based caching.
  • supports read-only or nonstrict read/write caching .
  • appropriate for applications those have more read operations than write operations.

2.4)JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)

  • is a powerful replicated and transactional cache.
  • useful when we need a true transaction-capable caching architecture .

3) Caching Stringategies

Important thing to remembered while studying this one is none of the cache providers support all of the cache concurrency strategies.

3.1) Read-only

  • Useful for data that is read frequently but never updated.
  • It is Simple .
  • Best performer among the all.
Advantage if this one is, It is safe for using in a cluster. Here is an example for using the read-only cache strategy.
1
2
3
4
<class name="abc.mutable " mutable="true ">
<cache usage="read-only"/>
....
</class>

3.2) Read-Write

  • Used when our data needs to be updated.
  • It’s having more overhead than read-only caches.
  • When Session.close() or Session.disconnect() is called the transaction should be completed in an environment where JTA is no used.
  • It is never used if serializable transaction isolation level is required.
  • In a JTA environment, for obtaining the JTA TransactionManager we must specify the property hibernate.transaction.manager_lookup_class.
  • To use it in a cluster the cache implementation must support locking.
Here is an example for using the read-write cache stringategy.
1
2
3
4
5
6
7
8
<class name="abc.xyz" .... >
<cache usage="read-write"/>
….
<set name="yuv" ... >
<cache usage="read-write"/>
….
</set>
</class>

3.3) Nonstrict read-write

  • Needed if the application needs to update data rarely.
  • we must specify hibernate.transaction.manager_lookup_class to use this in a JTA environment .
  • The transaction is completed when Session.close() or Session.disconnect() is called In other environments (except JTA) .
Here is an example for using the nonstrict read-write cache stringategy.
1
2
3
4
<class name="abc.xyz" .... >
<cache usage=" nonstringict-read-write"/>
….
</class>

3.4) Transactional

  • It supports only transactional cache providers such as JBoss TreeCache.
  • only used in JTA environment.

4) Configuration

For configuring cache the hibernate.cfg.xml file is used. A typical configuration file is shown below.
1
2
3
4
5
6
7
8
9
<hibernate-configuration>
    <session-factory>
        ...
        <property name="hibernate.cache.provider_class">
            org.hibernate.cache.EHCacheProvider
        </property>
        ...
    </session-factory>
</hibernate-configuration>
The name in <property> tag must be hibernate.cache.provider_class for activating second-level cache. We can use hibernate.cache.use_second_level_cache property, which allows you to activate and deactivate the second-level cache. By default, the second-level cache is activated and uses the EHCache.

5) <cache> element

The <cache> element of a class has the following form:
1
2
3
4
<cache
    usage=" caching stringategy"
    region="RegionName"
    include="all | non-lazy"/>
  • usage (mandatory) specifies the caching stringategy: transactional, read-write, nonstringict-read-write or read-only.
  • region (optional) specifies the name of the second level cache region .
  • include (optional) non-lazy specifies that properties of the entity mapped with lazy=”true” may not be cached when attribute-level lazy fetching is enabled.
The <cache> element of a class is also called as the collection mapping.

6) Caching the queries

Until now we saw only caching the transactions. Now we are going to study about the caching the queries.Suppose some queries are running frequently with same set of parameters, those queries can be cached. We have to set hibernate.cache.use_query_cache to true by calling Query.setCacheable(true) for enabling the query cache. Actually updates in the queries occur very often. So, for query caching, two cache regions are necessary.
  • For storing the results.( cache identifier values and results of value type only).
  • For storing the most recent updates.
Query cache always used second-level cache only. Queries wont cached by default. Here is an example implementation of query cache.
1
2
3
4
5
6
List xyz = abc.createQuery("Query")
    .setEntity("…",….)
    .setMaxResults(some integer)
    .setCacheable(true)
    .setCacheRegion("region name")
    .list();   
We can cache the exact results of a query by setting the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true as follows:
1
<property name="hibernate.cache.use_query_cache">true</property>
Then, we can use the setCacheable() method on any query we wish to cache.

7) Custom Cache

To understand the relation between cache and the application the cache implementation must generate statistics of cache usage.

7.1) Custom Cache Configuration

In the hibernate.properties file set the property hibernate.cache.provider_class = examples.customCache.customCacheProvider.

7.2) Implementation :: ExampleCustomCache

Here is the implementation of ExampleCustomCache. Here it uses Hashtable for storing the cache statistics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package examples.ExampleCustomCache;
import net.sf.hibernate.cache;
import org.apache.commons.logging;
public class ExampleCustomCache implements Cache
{
  public Log log = LogFactory.getLog(ExapleCustomCache.class);
  public Map table = new Hashtable(100);
int hits, misses, newhits, newmisses, locks, unlocks,
      remhits, remmisses, clears, destroys;
  public void statCount(StringBuffer input, String string1,
                                        int value)
  {
    input.append(string1 + " " + value);
  }
  public String lStats()
  {
    StringBuffer res = new StringBuffer();
    statCount(res, "hits", hits);
    statCount(res, "misses", misses);
    statCount(res, "new hits", newhits);
    statCount(res, "new misses", newmisses);
    statCount(res, "locks", lock);
    statCount(res, "unlocks", unlock);
    statCount(res, "rem hits ", remhits);
    statCount(res, "rem misses", remmisses);
    statCount(res, "clear", clears);
    statCount(res, "destroy", destroys);
    return res.toString();
  }
  public Object get(Object key)
  {
    if (table.get(key) == null)
    {
      log.info("get " + key.toString () + " missed");
      misses++;
    } else
    {
      log.info("get " + key.toString () + " hit");
      hits++;
    }
    return table.get(key);
  }
  public void put(Object key, Object value)
  {
    log.info("put " + key.toString ());
    if (table.containsKey(key))
    {
      newhits++;
    } else
    {
      newmisses++;
    }
    table.put(key, value);
  }
  public void remove(Object key)
  {
    log.info("remove " + key.toString ());
    if (table.containsKey(key))
    {
      remhits++;
    } else
    {
      remmisses++;
    }
    table.remove(key);
  }
  public void clear()
  {
    log.info("clear");
    clears++;
    table.clear();
  }
  public void destroy()
  {
    log.info("destringoy ");
    destroys++;
  }
  public void lock(Object key)
  {
    log.info("lock " + key.toStringing());
    locks++;
  }
  public void unlock(Object key)
  {
    log.info("unlock " + key.toStringing());
    unlocks++;
  }    
Here is the example of Custom Cache.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Package examples.ExapleCustomCache;
import java.util;
import net.sf.hibernate.cache;
public class ExampleCustomCacheProvider implements CacheProvider
{
  public Hashtable cacheList = new Hashtable();
  public Hashtable getCacheList()
  {
    return cacheList;
  }
  public Stringing cacheInfo ()
  {
    StringingBuffer aa = new StringingBuffer();
    Enumeration cList = cacheList.keys();
    while (cList.hasMoreElements())
    {
      Stringing cName = cList.nextElement().toStringing();
      aa.append(cName);
      ExapleCustomCache myCache = (ExapleCustomCache)
                  cacheList.get(cName);
      aa.append(myCache.lStats());
    }
    return aa.toStringing();
  }
  public ExampleCustomCacheProvider()
  {
  }
  public Cache bCache(String string2, Properties properties)
  {
    ExampleCustomCache nC = new ExapleCustomCache();
    cacheList.put(string2, nC);
    return nC;
  }
}

8)Something about Caching

8.1) Performance

Hibernate provides some metrics for measuring the performance of caching, which are all described in the Statistics interface API, in three categories:
  • Metrics related to the general Session usage.
  • Metrics related to the entities, collections, queries, and cache as a whole.
  • Detailed metrics related to a particular entity, collection, query or cache region.

8.2) About Caching

  • All objects those are passed to methods save(), update() or saveOrUpdate() or those you get from load(), get(), list(), iterate() or scroll() will be saved into cache.
  • flush() is used to synchronize the object with database and evict() is used to delete it from cache.
  • contains() used to find whether the object belongs to the cache or not.
  • Session.clear() used to delete all objects from the cache .
  • Suppose the query wants to force a refresh of its query cache region, we should call Query.setCacheMode(CacheMode.REFRESH).

9) Conclusion

Caching is good one and hibernate found a good way to implement it for improving its performance in web applications especially when more database traffic occurs. If we implement it very correctly, we will get our applications to be running at their maximum capacities. I will cover more about the caching implementations in my coming articles. Try to get full coding guidelines before going to implement this.