GlideRecord insert. Is .initialize() necessary?

Kyryl Petruk1
Tera Expert

Hi Everyone,

 

I've just been curious.

Wiki says this is a correct way to insert a record in a table using GlideRecord:

http://wiki.servicenow.com/index.php?title=GlideRecord#Insert_Methods

var gr = new GlideRecord('to_do');
gr.initialize(); 
gr.name = 'first to do item'; 
gr.description = 'learn about GlideRecord'; 
gr.insert();

 

But what actually gr.initialize() does?

What happens if I skip it? Will the record be created differently or simply slower?

On practice I don't see any difference, record is created properly.

 

Will appreciate your comments!

Thanks!

29 REPLIES 29

Why not use 'initialize()' in a loop?


The only thing 'initialize()' does is empty the variables, so of'course it can be used within a loop. When you want to create multiple records in a function, it is better to use initiliaze inside the loop than to create multiple objects with 'new GlideRecord', because it would use less memory.


Indeed, this was my thought and I have practiced this for a while without any issues. Thanks for the confirmation.


ccajohnson
Kilo Sage

What you are doing with initialize() is instantiating the glide record object. This allows you to populate the object with the appropriate values before actually inserting the object into the database.



I hope this is helpful,


Josh Cooper
ServiceNow Employee
ServiceNow Employee

To add my observations:



Initialize will grab a sys_id right away - so if you want to write it out then you can just assign it to a variable, because there's a sys_id associated already, you can also update() instead of insert(), and it will still work.


e.g.:


myNewGR.initialize();


var myID = myNewGR.sys_id;


myNewGR.update();



If you don't initialize, then you can't update, and need to insert.   At that point, if you want the sys_id, then you capture it by assigning the insert statement like


var myID = myNewGR.insert();



That's just based on my observations.