Skip to content

JavaScript object size bytes | Example code

  • by

Do loop through the object and check with the condition. If Condition will check typeof and add the byte for that. At the end of the function will return object size in bytes.

JavaScript object size bytes Example

HTML example code shows the full size of the object- “retained size”.

<!DOCTYPE HTML> 
<html> 
<body> 

	<script>
		const users = [
		{
			firstName: "Bruce",
			lastName: "Wayne",
			id: "1",
		},

		{
			firstName: "Peter",
			lastName: "Parker",
			id: "2"
		},

		{
			firstName: "Tony",
			lastName: "Stark",
			id: "3"
		}
		];

		function roughSizeOfObject( object ) {

			var objectList = [];
			var stack = [ object ];
			var bytes = 0;

			while ( stack.length ) {
				var value = stack.pop();

				if ( typeof value === 'boolean' ) {
					bytes += 4;
				}
				else if ( typeof value === 'string' ) {
					bytes += value.length * 2;
				}
				else if ( typeof value === 'number' ) {
					bytes += 8;
				}
				else if
					(
						typeof value === 'object'
						&& objectList.indexOf( value ) === -1
						)
				{
					objectList.push( value );

					for( var i in value ) {
						stack.push( value[ i ] );
					}
				}
			}
			return bytes;
		}

		console.log(roughSizeOfObject(users));
		
	</script>
</body> 
</html>	

Output:

JavaScript object size bytes

Do comment if you have any doubts and suggestions on this JS bytes topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading