What’s causing a memory leak here?

Could anyone please help me find what is the memory leak here? I don’t know how to find it but I’m sure there is one, because every time I run it the server gets slower!

Parse.Cloud.job("setupClubs", function() {
	var getPostsQuery = new Parse.Query(Parse.User);

	getUsersQuery.doesNotExist("clubs");
	getUsersQuery.select("objectId", "clubs");
	getUsersQuery.limit(2000);

	getUsersQuery.find({
		useMasterKey: true,
		success: function(usersArray) {
			console.log("usersArray " + usersArray.length + "\n\n");
			var clubs = [];

			for (var index = 0; index < usersArray.length; index++) {
				usersArray[index].set("clubs", []);
				
				// ---------------------------------

				const Club = Parse.Object.extend("Club");
				const clubObject = new Club();
			
				clubObject.set("name", "My club");
				clubObject.set("emoji", "🥳");
				clubObject.set("userId", usersArray[index].id);
				clubObject.set("type", "myClub");

				const custom_acl = new Parse.ACL();

				custom_acl.setPublicWriteAccess(false);
				custom_acl.setPublicReadAccess(false);

				clubObject.setACL(custom_acl);

				clubs.push(clubObject);
			}
			
			console.log("saving clubs\n\n");
			console.log(clubs[0]);
			Parse.Object.saveAll(clubs, {
				useMasterKey: true,
				success: function() {
					console.log("saved clubs\n\n");
			
					console.log("saving users\n\n");
					Parse.Object.saveAll(usersArray, {
						useMasterKey: true,
						success: function() {
							console.log("saved users\n\n");
						},
						error: function() {
				
						}
					});
				},
				error: function(error) {
					console.log("error saving clubs\n\n");
					console.log(error);
				}
			});
		},
		error: function(error) {

		}
	});
});

Move this line to outside the job scope: const Club = Parse.Object.extend("Club");

Use it only a single time in the beginning of the file.

Could you please explain why?

Every time this line runs (inside the loop), you are instantiating a new class, causing the memory leak. That’s not the right way to use Parse.Object.extend. Use it only once for each class in the beginning of the file, or use new Parse.Object('ClassName'), new Parse.Query('ClassName') without using the Parse.Object.extend.

1 Like

I get all that, but shouldn’t that be cleared when the job finishes?

Maybe the garbage collector can dispose it in some point in time but anyways there is no point in recurrently extending the same class. If you move this line out, you will even notice performance improvement in the job execution for a large userArray.

2 Likes

Related topic: Parse server performance loss after time
Related GitHub issue: Parse Server performance loss · Issue #7036 · parse-community/parse-server · GitHub