A token is a "placeholder" of the object or field it points to. It consumes very little resources, as compared to a describe, because it doesn't actually contain any information about the field or object, such as its label, data type, maximum length, etc. A describe can contain hundreds or even thousands of bytes of data, but a token is significantly smaller (less than 20 bytes).
To consider the savings, if you have 500 custom fields, 500 tokens might be 10,000 bytes of memory, while a full describe for all 500 fields would probably use closer to 500,000 bytes of memory.
As a bonus, you can also use tokens in place of strings when using the generic SObject methods get
and set
, which reduces the possibility of the system throwing an exception because of a typo; the fields are statically checked at compile-time.
As an example of the prior paragraph, consider this code:
Account a = new Account();
a.put('Nmae', 'Test'); // Run-time error
a.put(Account.Nmae, 'Test'); // Compile-time error
The first error might be harder to track down because it won't show up until you're testing, while the second one will surface immediately because of the compile-time checking.
Schema.DescribeSObjects()
is a function that returns full object-level details for one or more SObjects, such as the type of name field (text or auto-number), its singular and plural labels, and accessibility information. You can use this information to render strings dynamically, provide branch logic depending on the accessibility of the object for the current user, and more.
The return value (the result) of the function is one or more DescribeSObjectResult
objects that actually contains the describe information from DescribeSObjects
or Sobject.getDescribe()
.
There are two types of describes: DescribeSobjectResult
and DescribeFieldResult
. As they are named; the former contains data related to an entire SObject, such as its label and child relationships, while the latter contains information such as the formula used for default values, or picklist values).
Best Answer
in APIv26 there's a new method, Id.getSObjectType() which returns a sObject token you can use to find it's type. Sample code:
This new style uses much less heap space and
script statementsCPU time in addition to being much simpler and is highly recommended.Don't do this anymore, but traditionally you could use the global describe to check the key prefix of each sObject type against your record Id and if they matched you knew what type of record it is. A sample of doing this (shamlessly stolen from Andrew Fawcett):