BufferStrategy - CPU Usage

Is there a less CPU intensive way to create a double buffer, bec just now when am doing it this way it takes up 50-60% of CPU without it, it’s 10-20%.
I know i could use OpenGL or Slick etc… but am trying to create this whole thing without any Libraries (except System Library).


	public void draw() {
		if (this.getBufferStrategy() == null) {
			createBufferStrategy(2);
			return;
		}
		
		Graphics2D g = (Graphics2D) getBufferStrategy().getDrawGraphics();
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, WIDTH+2, HEIGHT);
		g.setColor(Color.white);
		g.setFont(new Font("Serif", Font.PLAIN, 14));
		g.drawString("Ups: " + this.Ups , 4, 12);
		g.drawString("FPS: " + this.frameRate , 4, 24);
//		for(int i = 0; i < test.length; i++){
//			if(getCurrentState().toLowerCase().contains(test[i].getClass().getSimpleName().toLowerCase())){
//				try {
//					Method m = test[i].getClass().getDeclaredMethod("draw", Graphics2D.class);
//					m.invoke(test[i], g);
//				}catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
//					System.out.println("graphics Error!");
//					System.out.println(e.toString());
//				}
//			}
//		}
		g.dispose();
		getBufferStrategy().show();
	}

Any information would be appreciated
Cheers

Do you limit FPS in any way? If you don’t, then you’ll always eat cpu…

also, the code you have commented uses reflection in a way that will be rather cpu intensive

Yeah, i have a limit to FPS,
The commented code isn’t really the problem i tested it out.
I’ve commented out each part to see what could be causing the issue and when i took away the BufferStrat it went down to 10-20%

Java2D often uses software (CPU) when rendering and requires high CPU usage for rendering a typical game scene (with many sprites, alpha, etc).

The best way to reduce load on CPU is to do more heavy lifting on the GPU. This means using an OpenGL based renderer.

“Performance” and “Java2D” don’t go so well together. Choose one or the other. :slight_smile:

With that said, here is how I used BufferStrategy in my last Java2D project:

 ... init ...
		//needs to be called after JFrame is valid and visible
		canvas.createBufferStrategy(2);
		strategy = canvas.getBufferStrategy();


 ... game loop ...

			update(deltaTime);

			do {
				do {
					Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
					//clear screen
					g.setColor(Color.white);
					g.clearRect(0, 0, width, height);
					render(g);
					g.dispose();
				} while (strategy.contentsRestored());
				strategy.show();
			} while (strategy.contentsLost());

Ah yeah should have known that :stuck_out_tongue:

Cheers for the code (nice way of doing it :slight_smile: ) & info