How to allocate 1MB in Scala

3 Answers

0 votes
// Allocates 1 MB = 1,048,576 bytes
val buffer: Array[Byte] = new Array[Byte](1024 * 1024) 

println(s"Allocated ${buffer.length} bytes.")



 
/*
run:

Allocated 1048576 bytes.

*/

 



answered May 20, 2025 by avibootz
0 votes
import java.nio.ByteBuffer

// Allocates 1 MB = 1,048,576 bytes
val byteBuffer: ByteBuffer = ByteBuffer.allocate(1024 * 1024) 

println(s"Allocated ${byteBuffer.capacity()} bytes.")



 
/*
run:

Allocated 1048576 bytes.

*/

 



answered May 20, 2025 by avibootz
0 votes
// Allocates 1MB = 1,048,576 bytes (assuming each Long is 8 bytes)

val largeArray: Array[Long] = new Array[Long](128 * 1024) 

println(s"Allocated ${largeArray.length * 8} bytes.")


 
/*
run:

Allocated 1048576 bytes.

*/

 



answered May 20, 2025 by avibootz

Related questions

3 answers 202 views
2 answers 152 views
1 answer 131 views
131 views asked May 20, 2025 by avibootz
3 answers 197 views
3 answers 204 views
204 views asked May 20, 2025 by avibootz
1 answer 112 views
112 views asked May 20, 2025 by avibootz
1 answer 113 views
113 views asked May 19, 2025 by avibootz
...