Latest Entries »

The 5 main differences betwen HashMap and Hashtable

HashMap and Hashtable both implement java.util.Map interface but there are some differences that Java developers must understand to write more efficient code. As of the Java 2 platform v1.2, Hashtable class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework.

One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.
One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don’t need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java.
HashMap does not guarantee that the order of the map will remain constant over time.
Note that HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

In Summary there are significant differences between Hashtable and HashMap in Java e.g. thread-safety and speed and based upon that only use Hashtable if you absolutely need thread-safety, if you are running Java 5 consider using ConcurrentHashMap in Java.

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.

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

 

I was just surfing across the web to test my html5 application.I found a beautiful site that i would like to share. I spend some good time on it  figured it out quite interesting.

People who are developing mobile web|Html5 based applications ,  Wandering whether their solution adopts 100% to the browsers available in the market and which browser supports what sort of features  ,tags etc..  Then the below specified site gives you perfect solution for all your queries.

They had specified even browser, browser comparison and points specified to the compatibility of HTML5 Support

So check it out you might find interesting too.

http://www.html5test.com

Thanks,

Shyam.S

You want to implement HTML5 features when they’re supported by the browser, but
degrade to another solution when they’re not.
Solution

Unfortunately, HTML5 currently comes with limited browser support. You may like
to implement some of these new technologies, but you also want to accommodate
browsers that don’t yet support them.
Modernizr (see http://modernizr.com) is a JavaScript library that makes it very easy to
do just that: it detects the availability of various HTML5 and CSS3 features within a
user’s browser.

<img src=”vscover.jpg” alt=”Veil &amp; Subdue: Courtship of the Black Sultan”/>
<div id=”caption”>
<div id=”audio”>
<audio>
<source src=”turnthepage.ogg”>
<source src=”turnthepage.mp3″ />
</audio>
<p><input type=button onclick=”playPause()” value=” ” tabindex=”0″ /> &ldquo;Turn the Page&rdquo; </div>
</div>

First, download the Modernizr JavaScript library from http://modernizr.com. Include
reference to this file within the <head> of your HTML document:
<script src=”js/modernizr-1.6.min.js”></script>

<script>
if (Modernizr.audio) {
function playPause() {
var myAudio = document.getElementsByTagName(‘audio’)[0];
if(myAudio.paused)
myAudio.play();
else
myAudio.pause();
}
}
When the audio element isn’t supported, Modernizr adds a “no-audio” class to the
header element. So, we can select for this class in our CSS, and set the display value for
“none” for any element we want to disappear.

</script>

jQTouch Vs Sencha Touch vs jQuery Mobile

I would like to add few more thoughts of mine which is found across www.

What is Sencha Touch?

Sencha Touch is the world’s first mobile web app development framework follows MVC built specifically to leverage HTML5, CSS3, and Javascript for the highest level of power, flexibility, and optimization. It make specific use of HTML5 to deliver components like audio and video, as well as a localStorage proxy for saving data offline. It makes extensive use of CSS3 in our stylesheets to provide the most robust styling layer possible.

Sencha Touch is a cross-platform framework aimed at next generation, touch enabled, devices. It’s currently compatible with Apple iOS 3+, Android 2.1+, and BlackBerry 6+ devices.

Altogether, the entire library is under 120kb (gzipped and minified), and it’s trivial to make that number even smaller by disabling unused components or styles.

Features of Sencha Touch
Easy Setup
Sencha Touch includes a set of graphical user interface GUI-based controls or “components” for use within mobile web applications. These components are highly optimized for touch input.
Built-in transition effects
Resolution Independent
Touch event management: It supports events like Tap, Double Tap, Pinch, Swipe and Scroll.
Application data support: Sencha Touch has a data package to support web standards for data interchange with servers such as Ajax and JSONP
Official Website
Differences
jQuery Mobile supports more number of mobile platform as compare to Sencha Touch. Sencha touch only supports iOS, Android and recently Blackberry.
jQuery Mobile and Sencha touch both provides great UI features with lots of control but Sencha touch wins here. Sencha Touch offers a bit more like lots of icons, or built-in maps.
jQuery Mobile is easy to use as Sencha Touch is completely Javascript. Your application takes place in js files, dealing with js classes. On the other hand, jQueryMobile is markup-driven. Sencha Touch is an extension of the Ext JS framework. It has a more native language feel than html and does not follow open standards. For example, the entire of a webpage is generated in javascript.
jQuery Mobile is easy to learn but for Sencha touch one need to put extra effort to learn it. In fact the documentation of Sencha touch is not comprehensive but jQuery Mobile documentation is quite good.
jQuery mobile is light weight compare to Sencha touch.
Sencha Touch supports a more MVC style application design, whereas jQuery mobile will simply be a load of markup and a load of jQuery script converting your HTML elements into touch friendly interface components.
jQuery Mobile Framework is easy to integrate with other technologies.
jQuery Mobile is free where Sencha Touch is available free of charge for commercial and open source application development. However, embedding Sencha Touch in a web application builder or software development kit (SDK) requires a paid commercial OEM license agreement. Read more about Sencha Touch Licensing FAQ.

Programming with sencha is not easy unless you come to know complete  ExtJs.But if you are purchasing their SDK then life becomes simpler.

For more info refer jquerybyexample.com

Love to program on mobile its quite easy and simple if you know little stuff of html,javascript.

if you are good in JavaScript then there you might be popular or million-er just tie your thoughts 

to your design  and publish to web :) Who know your solution might be the smart among the world. Then start…

Oh..! Whats Lacking is it a question can we do with html and js hmm… Perfect its right.

In order to achieve this you need to ++ of them. ++ mean the base is the same but just same additions.

Now ? What are they .

To design mobile application you need to know HTML++ i.e HTML5

Its just modification to existing html tags and quite easy to learn..

if you modify your tags according to html5 standards then you app is ready on desktop | Mobile | Tablet.

But are you fine with the content then how about the controls rendered on mobile do they need to optimized as per the mobile right ? and we need to interactions to them as well.

Yes, This can be achieved easily using JQueryMobile a perfect combination of Mobile Interface,Components,Controls and Interactions..

Learning JQM is quite easy just don’t explore the world and mess your self.

Just explore the below url.

http://jquerymobile.com/resources/#Articles

Thanks,

Shyam

 

 

 

 

 

 

 

 

 

“jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.”

http://jquery.com/

“jQuery offers a mechanism for adding in methods and functionality, bundled as plugins.”

http://docs.jquery.com/Plugins/Authoring

“jQuery UI provides abstractions for low-level interaction and high-level, themeable widgets, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.”

http://ui.jquery.com/

jQuery ( http://jquery.com/ )

So jQuery is a concise and minimal javascript framework. It covers the basics – DOM Manipulation, Events, Ajax, Animations. It does so quite nicely, and is rather popular.

Plugins ( http://plugins.jquery.com/ )

jQuery is extensible. Anyone can write code that gives jQuery more than just the basics functionality. These are packaged as plugins. In addition to including

jquery.js

you might also include a plugin file (that you or someone else wrote), such as

jquery.foo.js

This would typically add a function .foo() which you could call on any jQuery object as if that were a built-in basic capability of jQuery. You can find a huge number of plugins on

http://plugins.jquery.com/

as well as elsewhere on the internet. People write and release jQuery plugins all the time, because they’re easy to write and share. They cover things such as menus, rich media (audio/video), data handling, cookies, browser detection, layout, form validation. Anything people want, really.

When a plugin becomes so ubiquitous that nearly everyone is including it on their page with jquery.js, it can be a candidate for inclusion in jQuery core. But only where it is in demand, makes sense, and still keeps the library lightweight, easy to use, etc. That said, jQuery core will never grow beyond it’s fundamentals (hence the name, core). Enter jQuery UI.

jQuery UI ( http://ui.jquery.com/ )

A couple years back there was a set of quite popular jQuery plugins bundled in a package called Interface, written by Stefan Petre. These offered really great interactions, like drag-and-drop, selecting, sorting, resizing; widgets like tooltips, autocomplete, accordion. The 1.2 release of jQuery had some API changes that would’ve required changes to Interface, for it to be compatible, but Interface was never updated.

jQuery UI (started by Paul Bakaus) picked up where Interface left off. Many people are interested in a complete package/library of jQuery plugins with a common/consistent API, complete documentation, testing in all major browsers, with which they can build rich web interfaces and/or RIAs (Rich Internet Applications). Oh yeah, and they should work well together, be easy to use, accessible, extensible, and themeable. Whew.

I experimented with jQuery months ago, and
don’t remember seeing a UI version in the tutorials, is it new?

jQuery UI is a sister-project of jQuery. The 1.0 release of jQuery UI was September 2007. Version 1.5 was released in June 2008. You can get a pretty full history (including what went in to each release, and how it matured) on the jQuery Blog. The latest stable release is 1.5.2 and includes

Interactions
- Draggables (drag)
- Droppables (and drop)
- Resizables
- Selectables
- Sortables

Widgets
- Accordion
- Datepicker
- Dialog
- Slider
- Tabs

Effects
- blind, bounce, clip, drop down/up/left/right, explode, fold, highlight, pulsate, puff, scale, shake, slide down/up/left/right, transfer
- Color animations
- Class animations (addClass/removeClass/toggleClass w/Interval)

Some other notes:

There is documentation for all of jQuery UI, including how to theme each plugin

jQuery UI is hosted on google’s ajax libraries api

jQuery UI has full theming support for all plugins. The jQuery UI website even has an application for getting started building a theme, called ThemeRoller. It gives you a live preview of your theme applied to all the widgets as you create it.

The jQuery UI website has a Download Builder which allows you to pick and choose just the components you want, and wraps them up (with a bow, er min/pack compression options) in one file.

There are more plugins in the works such as:
- colorpicker
- autocomplete
- progressbar
- spinner
- menu
- toolbar
- panels
- splitters
- tree
- uploader
- grid
- tooltips

You can follow jQuery and jQuery UI on twitter and/or identica:

jQuery

http://twitter.com/jquery

http://identi.ca/jquery

jQuery UI

http://twitter.com/jqueryui

http://identi.ca/jqueryui

(both sites use jQuery :)

Lastly, is jQuery UI licensed the same way as the original jQuery?

Yes, jQuery UI (like jQuery) is dual-licensed MIT and GPL. See

http://jquery-ui.googlecode.com/svn/trunk/MIT-LICENSE.txt

http://jquery-ui.googlecode.com/svn/trunk/GPL-LICENSE.txt

meaning you can pick the one that suits you.

Richard D. Worth

jQuery Mobile Charts

The Plot Chart
Numeric data quickly becomes difficult for us humans to understand. Once the number of rows or columns in a table passes two or three, the meaning quickly becomes harder to grasp. The easiest way to give meaning to numeric data is to display it as a chart. Unfortunately jQuery Mobile doesn’t have any built-in charting capabilities and to the best of my knowledge there isn’t a jQuery Mobile charting plug-in available. But lucky for us, jQuery Mobile is built on top of jQuery and there are several charting plug-ins available for it.

My requirements for a charting library are pretty simple:
Free and open source
Compatible across the three mobile platforms I support: iOS, Android, Windows Phone 7
One of my favorite JavaScript charting libraries is “Raphael”. I have used it on desktop projects previously but it was quickly out of the running. Raphael uses SVG, which isn’t supported well across mobile platforms.

Next I googled, “jQuery charts”. Nearly 3 million websites were returned, so I knew I was going to find something. Close to the top of the list was the following link: 1st Web Designer. The post there listed six jQuery charting plug-ins:

GraphUp
jQuery Visualize
Highcharts
Flot
jQuery Sparklines
jqPlot
After doing a bit of analysis, I decided to run with jqPlot. This is not to say that the other packages aren’t good, it is just that I was able to understand jqPlot’s examples quicker than the others and it met all of my requirements. For your own needs, please try out the libraries, they may meet your needs better than they had mine.

jqPlot

There are two methods for generating graphics in HTML5, canvas and SVG.
Canvas is like a bitmap and JavaScript can render graphics to it. SVG’s use of vector graphics makes it seem ideal for a charting library, the problem is that SVG is not as well supported as canvas and it is not available on 2.x Android or any WP7. jqPlot uses HTML5 canvas.

The jqPlot library is huge. It has an immense number of features. But it is not a bloated pig, it is smartly architected. Rather than force you to download a lot of charts and features you won’t use, it, itself is composed of a large number of plug-ins, I counted 26 of them. This means you only download the plug-ins you want to use.

Following are the below selectors,filters which are used in common in jquery.
Below selectors are specified with correspoding purposes.

detttach :Temporarily Removes from the DOM.
remove : Removes Peremanently from the DOM.
append: Attach any content.
parent :Travelse to it parent level object.
children :Travelse to its beneath objects
prev : Travelse to the Left side of the elements.
Ex:-
.previous() it moves to the

next : Travelse to the Right side of the elements.
Ex:-
.next() it moves to the

replaceWith :This will replace the content.
$(“.meat”).replaceWith(”

  • Hai
  • “);

    Filter:
    1)first
    2)last
    3)slice:-slice(1,3) This returns the second element.
    4)not:- Returns all the Elements which doesnt pocess that quality.
    5)eq: Equals.
    Ex:-$(“.fish).eq(1);
    This returns the first element of fish class.
    6)before():
    Append a tag before the tag.
    $(“.fish”).before(”

  • Handsome
  • “);
    This will result putting Handsome before the fish.
    7) after()
    Append a tag before the tag.
    $(“.fish”).after(”

  • Handsome
  • “);
    This will result putting Handsome after the fish.
    8)not
    It will result all the children whose heading are not h4.
    Ex:-
    $(“.left_col”).children().not(“h4″);
    9) Filter()

    DOM manipulation You can add to, replace, and remove things from the DOM at will:
    detach
    remove
    replaceWith
    before
    after

    Filters
    Filter methods help you narrow down a set of selected elements:
    first
    equal
    last
    slice
    filter
    not

    Fade effects
    Change the opacity property of CSS
    elements: fadeInfadeOut
    fadeTo

    Slide effects
    Change the height property of CSS
    elements:
    slideUp
    slideDownslideToggle

    animate
    Lets you create custom animations when out-of-theboxjQuery effects aren’t enough.
    Animates CSS properties over time. Only works with CSS properties that have numerical settings.
    Elements can be moved either absolutely or relatively.
    Operator combinations (=, +, -) make relative animation much easier.

    –JQueryObject–
    planeObject={
    engines:”4″,
    type:”passenger”,
    propellor: “No”};

    Now we can acess the elements like planeObject.engines.

    var myCountry = {
    getCapital : function() {
    alert(this.myCapital);
    },
    myName : ‘USA’,
    myCapital : ‘Washington DC’
    },

    Now we can access the object in this fashion.
    myCountry.getCapital()
    this will show the alert message.
    This is soemthing like Class.methodname();

    $.inArray(): For identifying the element in the Array.
    Ex:-
    var haystack = new Array(‘hay’, ‘mouse’, ‘needle’, ‘pitchfork’)
    Synatax:
    var index = $.inArray( value, array );
    Identfying needle in the haystack.
    var needle_index = $.inArray( ‘needle’, haystack );

    On from Jquery 1.7.

    Ex:-Surfing all the elements under accepmenu whose elements are a
    $(‘#accpmenu’).on(‘click’, ‘a’, function () {

    //this gets the index by finding the first parent list-item element and getting it’s index compared do its siblings
    var selected_index = $(this).parents(‘li’).index();
    alert(selected_index);
    });

    Follow

    Get every new post delivered to your Inbox.